src/Controller/RdvController.php line 8734

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use DateTime;
  4. use DateInterval;
  5. use DateTimeZone;
  6. use Dompdf\Dompdf;
  7. use App\Entity\Rdv;
  8. use Dompdf\Options;
  9. use App\Entity\Lieu;
  10. use App\Entity\Audio;
  11. use App\Entity\Motif;
  12. use App\Entity\Referral;
  13. use App\Entity\Token;
  14. use Twig\Environment;
  15. use App\Entity\Centre;
  16. use App\Entity\Client;
  17. use \IntlDateFormatter;
  18. use App\Entity\CallLog;
  19. use App\Entity\EtatRdv;
  20. use App\Entity\LeadRdv;
  21. use App\Entity\Proches;
  22. use App\Entity\LieuTier;
  23. use App\Entity\RdvEvent;
  24. use App\Entity\AudioMotif;
  25. use App\Entity\CentreTier;
  26. use App\Entity\ClientTemp;
  27. use App\Entity\LeadStatus;
  28. use App\Entity\Remplacant;
  29. use App\Entity\TestClient;
  30. use App\Entity\AudioCentre;
  31. use App\Service\SmsHandler;
  32. use App\Entity\AccessCentre;
  33. use App\Entity\ClientStatus;
  34. use Psr\Log\LoggerInterface;
  35. use App\Entity\ClientBlocked;
  36. use App\Entity\CentreMutuelle;
  37. use App\Entity\LieuPrestation;
  38. use App\Entity\AudioSpecialite;
  39. use App\Entity\CallInteraction;
  40. use App\Service\PublicFunction;
  41. use App\Entity\CentrePrestation;
  42. use App\Entity\RegionDepartment;
  43. use App\Repository\RdvRepository;
  44. use Symfony\Component\Mime\Email;
  45. use App\Entity\Device\ClientDevice;
  46. use App\Entity\Notification\RdvSms;
  47. use App\Service\Lead\TwilioService;
  48. use App\Service\Lead\WhatsappService;
  49. use App\Entity\SynchronisationSetting;
  50. use App\Service\Lead\SynthflowService;
  51. use App\Service\Lead\ElevenLabsService;
  52. use Doctrine\ORM\EntityManagerInterface;
  53. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  54. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  55. use Symfony\Contracts\Cache\ItemInterface;
  56. use App\Service\Cosium\ClientCosiumService;
  57. use App\Service\Notification\RdvSmsService;
  58. use App\Entity\SpecificSubscription;
  59. use Symfony\Contracts\Cache\CacheInterface;
  60. use App\Entity\Synchronisation\CosiumCenter;
  61. use App\Service\Lead\AppointmentCallService;
  62. use Symfony\Component\Filesystem\Filesystem;
  63. use Symfony\Component\HttpFoundation\Request;
  64. use Symfony\Component\Mailer\MailerInterface;
  65. use Symfony\Component\HttpFoundation\Response;
  66. use Symfony\Component\Routing\Annotation\Route;
  67. use Doctrine\Common\Collections\ArrayCollection;
  68. use App\EasyAdmin\Controller\DashboardController;
  69. use Symfony\Component\HttpKernel\KernelInterface;
  70. use Symfony\Component\HttpFoundation\JsonResponse;
  71. use App\EasyAdmin\Controller\LeadRdvCrudController;
  72. use App\Service\AdsCompany\RepresentativeCdaService;
  73. use App\Entity\Synchronisation\SynchronisationCosium;
  74. use App\Service\GoogleCalendar\GoogleCalendarService;
  75. use App\EasyAdmin\Controller\RdvMyAudioCrudController;
  76. use App\Service\Notification\EmailNotificationService;
  77. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  78. use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGenerator;
  79. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  80. use Symfony\Component\Mercure\PublisherInterface;
  81. use Symfony\Component\Mercure\Update;
  82. use App\Service\Mercure\MercureService;
  83. class RdvController extends AbstractController
  84. {
  85.     private $emailNotificationService;
  86.     private $clientCosiumService;
  87.     private $rdvRepository;
  88.     private $entityManager;
  89.     private $cache;
  90.     private $mercure;
  91.     private $twig;
  92.     private AdminUrlGenerator $adminUrlGenerator;
  93.     private WhatsappService $whatsapp;
  94.     private LoggerInterface $logger;  // Service de journalisation
  95.     private RdvRepository $rdvRepo;
  96.     public function __construct(CacheInterface $cacheEntityManagerInterface $entityManagerRdvRepository $rdvRepoEmailNotificationService $emailNotificationServiceClientCosiumService $clientCosiumServiceRdvRepository $rdvRepositoryEnvironment $twigAdminUrlGenerator $adminUrlGeneratorWhatsappService $whatsappLoggerInterface $logger,MercureService $mercure)
  97.     {
  98.         $this->entityManager $entityManager;
  99.         $this->emailNotificationService $emailNotificationService;
  100.         $this->clientCosiumService $clientCosiumService;
  101.         $this->rdvRepository $rdvRepository;
  102.         $this->cache $cache;
  103.         $this->twig $twig;
  104.         $this->adminUrlGenerator $adminUrlGenerator;
  105.         $this->whatsapp $whatsapp;
  106.         $this->logger $logger;
  107.         $this->rdvRepo $rdvRepo;
  108.         $this->mercure $mercure;
  109.     }
  110.     /**
  111.      * @Route("/rdv/{id}", name="deleteRdvByID", methods={"DELETE"})
  112.      */
  113.     public function deleteRdvByID(Request $requestRdv $rdvGoogleCalendarService $googleCalendar)
  114.     {
  115.         if (!$request->query->get('token')) {
  116.             return new Response(json_encode([
  117.                 "message" => "Pas de token n'a été spécifié",
  118.                 "status" => 401,
  119.             ]), 401);
  120.         }
  121.         $entityManager $this->getDoctrine()->getManager();
  122.         /** @var Token */
  123.         $token $this->getDoctrine()
  124.             ->getRepository(Token::class)
  125.             ->findOneBy(['token' => $request->query->get('token')]);
  126.         if (!$token) {
  127.             return new Response(json_encode([
  128.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  129.                 "status" => 404,
  130.             ]), 404);
  131.         }
  132.         // get token age
  133.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  134.         // if the token if older than 7 days
  135.         if ($dateDiff->7) {
  136.             $entityManager->remove($token);
  137.             $entityManager->flush();
  138.             return $this->json([
  139.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  140.                 'path' => 'src/Controller/ClientController.php',
  141.                 "status" => 401,
  142.             ], 401);
  143.         }
  144.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  145.             return new Response(json_encode([
  146.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  147.                 "status" => 404,
  148.             ]), 404);
  149.         }
  150.         $entityManager->remove($rdv);
  151.         $entityManager->flush();
  152.         return new Response(json_encode(([
  153.             'message' => "Rdv has been successfully deleted",
  154.             "status" => 200,
  155.         ])));
  156.     }
  157.     /**
  158.      * @Route("/rdv/{id}", name="getRdvByID", methods={"GET","HEAD"})
  159.      */
  160.     public function getRdvByID(Request $requestRdv $rdvPublicFunction $publicFunction)
  161.     {
  162.         if (!$request->query->get('token')) {
  163.             return new Response(json_encode([
  164.                 "message" => "Pas de token n'a été spécifié",
  165.                 "status" => 401,
  166.             ]), 401);
  167.         }
  168.         $entityManager $this->getDoctrine()->getManager();
  169.         /** @var Token */
  170.         $token $this->getDoctrine()
  171.             ->getRepository(Token::class)
  172.             ->findOneBy(['token' => $request->query->get('token')]);
  173.         if (!$token) {
  174.             return new Response(json_encode([
  175.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  176.                 "status" => 404,
  177.             ]), 404);
  178.         }
  179.         // get token age
  180.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  181.         // if the token if older than 7 days
  182.         if ($dateDiff->7) {
  183.             $entityManager->remove($token);
  184.             $entityManager->flush();
  185.             return $this->json([
  186.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  187.                 'path' => 'src/Controller/ClientController.php',
  188.                 "status" => 401,
  189.             ], 401);
  190.         }
  191.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  192.             return new Response(json_encode([
  193.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  194.                 "status" => 404,
  195.             ]), 404);
  196.         }
  197.         /** @var AudioCentre */
  198.         $liaison $this->getDoctrine()->getRepository(AudioCentre::class)
  199.             ->findOneBy(array('id_audio' => $rdv->getIdAudio(), 'id_centre' => $rdv->getIdCentre(), 'isConfirmed' => true));
  200.         // Motif filter
  201.         /** @var AudioMotif[] */
  202.         $motifs $this->getDoctrine()->getRepository(AudioMotif::class)
  203.             ->findBy(array('id_audio' => $rdv->getIdAudio(), 'id_motif' => $rdv->getIdMotif()));
  204.         $resultMotif = new ArrayCollection();
  205.         foreach ($motifs as $motif) {
  206.             $resultMotif->add([
  207.                 "id" => $motif->getIdMotif()->getId(),
  208.                 "titre" => $motif->getIdMotif()->getTitre(),
  209.                 "consigne" => $motif->getConsigne(),
  210.                 "duration" => $motif->getDuration(),
  211.             ]);
  212.         }
  213.         // Specialities
  214.         /** @var AudioSpecialite[] */
  215.         $specialities $this->getDoctrine()->getRepository(AudioSpecialite::class)
  216.             ->findBy(array('id_audio' => $rdv->getIdAudio()));
  217.         $resultSpeciality = new ArrayCollection();
  218.         foreach ($specialities as $speciality) {
  219.             $resultSpeciality->add([
  220.                 "id" => $speciality->getIdSpecialite()->getId(),
  221.                 "titre" => $speciality->getIdSpecialite()->getLibelle(),
  222.             ]);
  223.         }
  224.         if ($rdv->getIdCentre())
  225.         /** @var AccessCentre*/
  226.         {
  227.             $accessCentre $this->getDoctrine()->getRepository(AccessCentre::class)
  228.                 ->findOneBy(array('id_centre' => $rdv->getIdCentre()));
  229.         } else
  230.         /** @var AccessCentre*/
  231.         {
  232.             $accessCentre $this->getDoctrine()->getRepository(AccessCentre::class)
  233.                 ->findOneBy(array('id_lieu' => $rdv->getIdLieu()));
  234.         }
  235.         if ($rdv->getIdCentre())
  236.         /** @var CentrePrestation[]*/
  237.         {
  238.             $prestations $this->getDoctrine()->getRepository(CentrePrestation::class)
  239.                 ->findBy(array('id_centre' => $liaison->getIdCentre()->getId()));
  240.         } else
  241.         /** @var LieuPrestation[]*/
  242.         {
  243.             $prestations $this->getDoctrine()->getRepository(LieuPrestation::class)
  244.                 ->findBy(array('id_lieu' => $rdv->getIdLieu()));
  245.         }
  246.         $resultPrestation = new ArrayCollection();
  247.         foreach ($prestations as $prestation) {
  248.             $resultPrestation->add([
  249.                 "id" => $prestation->getIdPrestation()->getId(),
  250.                 "titre" => $prestation->getIdPrestation()->getLibelle(),
  251.             ]);
  252.         }
  253.         $mutuelles $this->getDoctrine()->getRepository(CentreMutuelle::class)
  254.             ->findBy(array('id_centre' => $rdv->getIdCentre()));
  255.         $resultMutuelle = new ArrayCollection();
  256.         foreach ($mutuelles as $mutuelle) {
  257.             $resultMutuelle->add([
  258.                 "id" => $mutuelle->getIdMutuelle()->getId(),
  259.                 "titre" => $mutuelle->getIdMutuelle()->getLibelle(),
  260.             ]);
  261.         }
  262.         if ($rdv->getIdCentre())
  263.         /** @var CentreTier[]*/
  264.         {
  265.             $tiers $this->getDoctrine()->getRepository(CentreTier::class)
  266.                 ->findBy(array('id_centre' => $liaison->getIdCentre()->getId()));
  267.         } else
  268.         /** @var LieuTier[]*/
  269.         {
  270.             $tiers $this->getDoctrine()->getRepository(LieuTier::class)
  271.                 ->findBy(array('id_lieu' => $rdv->getIdLieu()));
  272.         }
  273.         $resultTier = new ArrayCollection();
  274.         foreach ($tiers as $tier) {
  275.             $resultTier->add([
  276.                 "id" => $tier->getIdTier()->getId(),
  277.                 "titre" => $tier->getIdTier()->getLibelle(),
  278.             ]);
  279.         }
  280.         $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  281.         /** @var Rdv[] */
  282.         $audioRdvs $this->getDoctrine()->getRepository(Rdv::class)
  283.             ->findAllReviewsAudio($rdv->getIdAudio()->getId());
  284.         /** @var Rdv[] */
  285.         $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  286.             ->findAllReviewsCentre($rdvCentre->getId());
  287.         // Comment
  288.         /** @var Rdv[] */
  289.         $rdvs $this->getDoctrine()->getRepository(Rdv::class)
  290.             ->findBy(array('id_audio' => $rdv->getIdAudio()));
  291.         $comments = [];
  292.         foreach ($rdvs as $rdv)
  293.             if ($rdv->getComment() && $rdv->getReview() && $rdv->getIdClient())
  294.                 array_push($comments, [
  295.                     "id" => $rdv->getIdClient()->getId(),
  296.                     "name" => $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname()[0] . ".",
  297.                     "comment" => $rdv->getComment(),
  298.                     "isMale" => $rdv->getIdClient()->getCivilite() == "Monsieur",
  299.                     "review" => $rdv->getReview(),
  300.                 ]);
  301.         return new Response(json_encode(([
  302.             "id" => $rdv->getId(),
  303.             "motif_id" => $rdv->getIdMotif()->getId(),
  304.             "motif_titre" => $rdv->getIdMotif()->getTitre(),
  305.             "audio_id" => $rdv->getIdAudio()->getId(),
  306.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  307.             "client_id" => $rdv->getIdClient()->getId(),
  308.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  309.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  310.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  311.             "etat_id" => $rdv->getIdEtat()->getId(),
  312.             "date" => $rdv->getDate(),
  313.             "comment" => $rdv->getComment(),
  314.             "review" => $rdv->getReview(),
  315.             "note" => $rdv->getNote(),
  316.             "testclient" => $rdv->getTestClient() ? [
  317.                 "result" => $rdv->getTestClient()->getResultTonal(),
  318.                 "date" => $rdv->getTestClient()->getDate(),
  319.                 "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  320.             ] : null,
  321.             "comments" => $comments,
  322.             "audio" => [
  323.                 "id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : $rdv->getIdAudio()->getId(),
  324.                 "civilite" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getCivilite() : $rdv->getIdAudio()->getCivilite(),
  325.                 "name" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getName() : $rdv->getIdAudio()->getName(),
  326.                 "lastname" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getLastname() : $rdv->getIdAudio()->getLastname(),
  327.                 "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  328.                 "mail" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getMail() : $rdv->getIdAudio()->getMail(),
  329.                 "phone" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getPhone() : $rdv->getIdAudio()->getPhone(),
  330.                 "adeli" => $rdv->getIdAudio()->getAdeli(),
  331.                 "pin" => $rdv->getIdAudio()->getPin(),
  332.                 "description" => $rdv->getIdAudio()->getDescription(),
  333.                 "averageRating" => $publicFunction->calculateRating($audioRdvs),
  334.                 "nbrReview" => count($audioRdvs),
  335.                 "motifs" => $resultMotif->toArray(),
  336.                 "specialities" => $resultSpeciality->toArray(),
  337.             ],
  338.             "centre" => [
  339.                 "id" => $rdvCentre->getId(),
  340.                 "audio_id" => $rdvCentre->getIdGerant()->getId(),
  341.                 "name" => $rdvCentre->getName(),
  342.                 "imgUrl" => $rdvCentre->getImgUrl(),
  343.                 "isRdvDomicile" => $rdv->getIdCentre() ? $rdvCentre->getIsRdvDomicile() : $rdv->getIdAudio()->getIsRdvDomicileIndie(),
  344.                 "address" => $rdvCentre->getAddress(),
  345.                 "postale" => $rdvCentre->getPostale(),
  346.                 "city" => $rdvCentre->getCity(),
  347.                 "finess" => $rdvCentre->getFiness(),
  348.                 "siret" => $rdvCentre->getSiret(),
  349.                 "website" => $rdvCentre->getWebsite(),
  350.                 "phone" => $rdvCentre->getPhone(),
  351.                 "isHandicap" => $rdvCentre->getIsHandicap(),
  352.                 "longitude" => $rdvCentre->getLongitude(),
  353.                 "latitude" => $rdvCentre->getLatitude(),
  354.                 "averageRating" => $publicFunction->calculateRating($centreRdvs),
  355.                 "nbrReview" => count($centreRdvs),
  356.                 "tram" => $accessCentre->getTram(),
  357.                 "rer" => $accessCentre->getRer(),
  358.                 "metro" => $accessCentre->getMetro(),
  359.                 "bus" => $accessCentre->getBus(),
  360.                 "parking" => $accessCentre->getParkingPublic(),
  361.                 "description" => $rdv->getIdCentre()->getDescription(),
  362.                 "parkingPrivate" => $accessCentre->getParkingPrivate(),
  363.                 "other" => $accessCentre->getOther(),
  364.                 "prestations" => $resultPrestation->toArray(),
  365.                 "mutuelles" => $resultMutuelle->toArray(),
  366.                 "tiers" => $resultTier->toArray(),
  367.                 "isLieu" => false,
  368.                 "schedule" => $rdv->getIdAudio()->getIsIndie() == false $rdv->getIdCentre()->getHoraire() : ($rdv->getIdLieu() ? $rdv->getIdLieu()->getHoraire() : $liaison->getHoraire()),
  369.             ],
  370.             "status" => 200,
  371.         ])));
  372.     }
  373.     /**
  374.      * @Route("/rdvs/client/{id}", name="getRdvsByClientID", methods={"GET","HEAD"})
  375.      */
  376.     public function getRdvsByClientID(Request $requestClient $clientPublicFunction $publicFunction)
  377.     {
  378.         if (!$request->query->get('token')) {
  379.             return new Response(json_encode([
  380.                 "message" => "Pas de token n'a été spécifié",
  381.                 "status" => 401,
  382.             ]), 401);
  383.         }
  384.         $entityManager $this->getDoctrine()->getManager();
  385.         /** @var Token */
  386.         $token $this->getDoctrine()
  387.             ->getRepository(Token::class)
  388.             ->findOneBy(['token' => $request->query->get('token')]);
  389.         if (!$token) {
  390.             return new Response(json_encode([
  391.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  392.                 "status" => 404,
  393.             ]), 404);
  394.         }
  395.         // get token age
  396.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  397.         // if the token if older than 7 days
  398.         if ($dateDiff->7) {
  399.             $entityManager->remove($token);
  400.             $entityManager->flush();
  401.             return $this->json([
  402.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  403.                 'path' => 'src/Controller/ClientController.php',
  404.                 "status" => 401,
  405.             ], 401);
  406.         }
  407.         if ($token->getIdClient()) {
  408.             if ($client != $token->getIdClient()) {
  409.                 return new Response(json_encode([
  410.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  411.                     "status" => 404,
  412.                 ]), 404);
  413.             }
  414.         } else if ($token->getIdAudio()) {
  415.             /** @var Token */
  416.             $token $this->getDoctrine()
  417.                 ->getRepository(Rdv::class)
  418.                 ->findOneBy(['id_client' => $client'id_audio' => $token->getIdAudio()]);
  419.             if ($client != $token->getIdClient()) {
  420.                 return new Response(json_encode([
  421.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  422.                     "status" => 404,
  423.                 ]), 404);
  424.             }
  425.         } else {
  426.             return new Response(json_encode([
  427.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  428.                 "status" => 404,
  429.             ]), 404);
  430.         }
  431.         if ($request->query->get('audio')) {
  432.             /** @var Rdv[] */
  433.             $rdvs $this->getDoctrine()
  434.                 ->getRepository(Rdv::class)
  435.                 ->findBy(['id_client' => $client->getId(), 'id_audio' => $token->getIdAudio()]);
  436.             $rdvResult = new ArrayCollection();
  437.         } else {
  438.             /** @var Rdv[] */
  439.             $rdvs $this->getDoctrine()
  440.                 ->getRepository(Rdv::class)
  441.                 ->findBy(['id_client' => $client->getId()]);
  442.             $rdvResult = new ArrayCollection();
  443.         }
  444.         if ($request->query->get('old')) {
  445.             $oldRdvResult = new ArrayCollection();
  446.         }
  447.         foreach ($rdvs as $rdv) {
  448.             if ($rdv->getIdEtat()->getId() != 1) {
  449.                 continue;
  450.             }
  451.             /** @var AudioMotif */
  452.             $audioMotif $this->getDoctrine()
  453.                 ->getRepository(AudioMotif::class)
  454.                 ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  455.             if (!$audioMotif) {
  456.                 continue;
  457.             }
  458.             $duration '';
  459.             if (is_null($rdv->getDuration())) {
  460.                 $duration $audioMotif->getDuration();
  461.             } else {
  462.                 $duration $rdv->getDuration();
  463.             }
  464.             $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  465.             /** @var Rdv[] */
  466.             $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  467.                 ->findAllReviewsCentre($rdvCentre->getId());
  468.             $rdvItem = [
  469.                 "id" => $rdv->getId(),
  470.                 "motif_id" => $rdv->getIdMotif()->getId(),
  471.                 "duration" => $duration,
  472.                 "color" => $audioMotif->getColor(),
  473.                 "audio_id" => $rdv->getIdAudio()->getId(),
  474.                 "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  475.                 "audio_name" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getName() . " " $rdv->getRemplacant()->getLastname() : $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  476.                 "client_id" => $rdv->getIdClient()->getId(),
  477.                 "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() . " " $rdv->getIdProche()->getLastname() : $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname(),
  478.                 "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  479.                 "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  480.                 "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  481.                 "testclient" => $rdv->getTestClient() ? [
  482.                     "result" => $rdv->getTestClient()->getResultTonal(),
  483.                     "date" => $rdv->getTestClient()->getDate(),
  484.                     "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  485.                 ] : null,
  486.                 "name" => $rdvCentre->getName(),
  487.                 "phone" => $rdvCentre->getPhone(),
  488.                 "imgUrl" => $rdvCentre->getImgUrl(),
  489.                 "address" => $rdvCentre->getAddress(),
  490.                 "postale" => $rdvCentre->getPostale(),
  491.                 "city" => $rdvCentre->getCity(),
  492.                 "etat_id" => $rdvCentre->getId(),
  493.                 "averageRating" => $publicFunction->calculateRating($centreRdvs),
  494.                 "nbrReview" => count($centreRdvs),
  495.                 "acceptedCurrency" => "CB Chèque",
  496.                 "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  497.                 "note" => $rdv->getNote(),
  498.                 "comment" => $rdv->getComment(),
  499.                 "review" => $rdv->getReview(),
  500.             ];
  501.             if ($rdv->getDate() >= new DateTime()) {
  502.                 $rdvResult->add($rdvItem);
  503.             } else if ($request->query->get('old')) {
  504.                 $oldRdvResult->add($rdvItem);
  505.             }
  506.         }
  507.         if ($request->query->get('old')) {
  508.             if ($request->query->get('onlyOld')) {
  509.                 if (count($rdvResult) > || count($oldRdvResult) > 0) {
  510.                     return new Response(json_encode(([
  511.                         "oldRdv" => $oldRdvResult->toArray(),
  512.                         "status" => 200,
  513.                     ])));
  514.                 } else {
  515.                     return new Response(json_encode(([
  516.                         "message" => "Aucun rendez-vous n'a été trouvé!",
  517.                         "test" => "count:" count($rdvs),
  518.                         'path' => 'src/Controller/RdvController.php',
  519.                         "rdv" => array(),
  520.                         "oldRdv" => array(),
  521.                         "status" => 404,
  522.                     ])));
  523.                 }
  524.             } else {
  525.                 if (count($rdvResult) > || count($oldRdvResult) > 0) {
  526.                     return new Response(json_encode(([
  527.                         "rdv" => $rdvResult->toArray(),
  528.                         "oldRdv" => $oldRdvResult->toArray(),
  529.                         "status" => 200,
  530.                     ])));
  531.                 } else {
  532.                     return new Response(json_encode(([
  533.                         "message" => "Aucun rendez-vous n'a été trouvé!",
  534.                         "test" => "count:" count($rdvs),
  535.                         'path' => 'src/Controller/RdvController.php',
  536.                         "rdv" => array(),
  537.                         "oldRdv" => array(),
  538.                         "status" => 404,
  539.                     ])));
  540.                 }
  541.             }
  542.         } else {
  543.             if (count($rdvResult) > 0) {
  544.                 return new Response(json_encode(([
  545.                     "content" => $rdvResult->toArray(),
  546.                     "status" => 200,
  547.                 ])));
  548.             } else {
  549.                 return new Response(json_encode(([
  550.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  551.                     "test" => "count2:" count($rdvs),
  552.                     'path' => 'src/Controller/RdvController.php',
  553.                     "status" => 404,
  554.                 ])));
  555.             }
  556.         }
  557.     }
  558.     /**
  559.      * @Route("/rdvs/client/{id}/centre", name="getRdvsByClientIDForCentre", methods={"GET","HEAD"})
  560.      */
  561.     public function getRdvsByClientIDForCentre(Request $requestClient $clientPublicFunction $publicFunction)
  562.     {
  563.         if (!$request->query->get('token')) {
  564.             return new Response(json_encode([
  565.                 "message" => "Pas de token n'a été spécifié",
  566.                 "status" => 401,
  567.             ]), 401);
  568.         }
  569.         $entityManager $this->getDoctrine()->getManager();
  570.         /** @var Token */
  571.         $token $this->getDoctrine()
  572.             ->getRepository(Token::class)
  573.             ->findOneBy(['token' => $request->query->get('token')]);
  574.         if (!$token) {
  575.             return new Response(json_encode([
  576.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  577.                 "status" => 404,
  578.             ]), 404);
  579.         }
  580.         $audio $this->getDoctrine()
  581.             ->getRepository(Audio::class)
  582.             ->findOneBy(['id' => $request->query->get('audio')]);
  583.         $audioCentre $this->getDoctrine()
  584.             ->getRepository(AudioCentre::class)
  585.             ->findOneBy(['id_audio' => $audio]);
  586.         // get token age
  587.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  588.         // if the token if older than 7 days
  589.         if ($dateDiff->7) {
  590.             $entityManager->remove($token);
  591.             $entityManager->flush();
  592.             return $this->json([
  593.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  594.                 'path' => 'src/Controller/ClientController.php',
  595.                 "status" => 401,
  596.             ], 401);
  597.         }
  598.         if ($token->getIdClient()) {
  599.             if ($client != $token->getIdClient()) {
  600.                 return new Response(json_encode([
  601.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  602.                     "status" => 404,
  603.                 ]), 404);
  604.             }
  605.         } else if ($token->getIdAudio()) {
  606.             /** @var Token */
  607.             if ($token->getIdAudio() != $audio) {
  608.                 return new Response(json_encode([
  609.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  610.                     "status" => 404,
  611.                 ]), 404);
  612.             }
  613.         } else {
  614.             return new Response(json_encode([
  615.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  616.                 "status" => 404,
  617.             ]), 404);
  618.         }
  619.         if ($request->query->get('centre')) {
  620.             /** @var Rdv[] */
  621.             $rdvs $this->getDoctrine()
  622.                 ->getRepository(Rdv::class)
  623.                 ->findBy(['id_client' => $client->getId(), 'id_centre' => $audioCentre->getIdCentre()]);
  624.             $rdvResult = new ArrayCollection();
  625.         } else {
  626.             /** @var Rdv[] */
  627.             $rdvs $this->getDoctrine()
  628.                 ->getRepository(Rdv::class)
  629.                 ->findBy(['id_client' => $client->getId()]);
  630.             $rdvResult = new ArrayCollection();
  631.         }
  632.         if ($request->query->get('old')) {
  633.             $oldRdvResult = new ArrayCollection();
  634.         }
  635.         foreach ($rdvs as $rdv) {
  636.             /*if ($rdv->getIdEtat()->getId() != 1) {
  637.                 continue;
  638.             }*/
  639.             /** @var AudioMotif */
  640.             $audioMotif $this->getDoctrine()
  641.                 ->getRepository(AudioMotif::class)
  642.                 ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  643.             if (!$audioMotif) {
  644.                 continue;
  645.             }
  646.             $duration '';
  647.             if (is_null($rdv->getDuration())) {
  648.                 $duration $audioMotif->getDuration();
  649.             } else {
  650.                 $duration $rdv->getDuration();
  651.             }
  652.             $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  653.             /** @var Rdv[] */
  654.             $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  655.                 ->findAllReviewsCentre($rdvCentre->getId());
  656.             $rdvItem = [
  657.                 "id" => $rdv->getId(),
  658.                 "motif_id" => $rdv->getIdMotif()->getId(),
  659.                 "duration" => $duration,
  660.                 "color" => $audioMotif->getColor(),
  661.                 "audio_id" => $rdv->getIdAudio()->getId(),
  662.                 "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  663.                 "audio_name" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getName() . " " $rdv->getRemplacant()->getLastname() : $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  664.                 "client_id" => $rdv->getIdClient()->getId(),
  665.                 "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() . " " $rdv->getIdProche()->getLastname() : $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname(),
  666.                 "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  667.                 "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  668.                 "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  669.                 "testclient" => $rdv->getTestClient() ? [
  670.                     "result" => $rdv->getTestClient()->getResultTonal(),
  671.                     "date" => $rdv->getTestClient()->getDate(),
  672.                     "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  673.                 ] : null,
  674.                 "name" => $rdvCentre->getName(),
  675.                 "phone" => $rdvCentre->getPhone(),
  676.                 "imgUrl" => $rdvCentre->getImgUrl(),
  677.                 "address" => $rdvCentre->getAddress(),
  678.                 "postale" => $rdvCentre->getPostale(),
  679.                 "city" => $rdvCentre->getCity(),
  680.                 "etat_id" => $rdvCentre->getId(),
  681.                 "averageRating" => $publicFunction->calculateRating($centreRdvs),
  682.                 "nbrReview" => count($centreRdvs),
  683.                 "acceptedCurrency" => "CB Chèque",
  684.                 "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  685.                 "note" => $rdv->getNote(),
  686.                 "comment" => $rdv->getComment(),
  687.                 "review" => $rdv->getReview(),
  688.                 "status" => $rdv->getIdEtat()->getLibelle()
  689.             ];
  690.             // dd(new DateTime());
  691.             if ($rdv->getDate() >= new DateTime()) {
  692.                 $rdvResult->add($rdvItem);
  693.             } else if ($request->query->get('old')) {
  694.                 $oldRdvResult->add($rdvItem);
  695.             }
  696.         }
  697.         if ($request->query->get('old')) {
  698.             if (count($rdvResult) > || count($oldRdvResult) > 0) {
  699.                 return new Response(json_encode(([
  700.                     "rdv" => $rdvResult->toArray(),
  701.                     "oldRdv" => $oldRdvResult->toArray(),
  702.                     "status" => 200,
  703.                 ])));
  704.             } else {
  705.                 return new Response(json_encode(([
  706.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  707.                     "test" => "count:" count($rdvs),
  708.                     'path' => 'src/Controller/RdvController.php',
  709.                     "status" => 404,
  710.                 ])), 404);
  711.             }
  712.         } else {
  713.             if (count($rdvResult) > 0) {
  714.                 return new Response(json_encode(([
  715.                     "content" => $rdvResult->toArray(),
  716.                     "status" => 200,
  717.                 ])));
  718.             } else {
  719.                 return new Response(json_encode(([
  720.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  721.                     "test" => "count2:" count($rdvs),
  722.                     'path' => 'src/Controller/RdvController.php',
  723.                     "status" => 404,
  724.                 ])));
  725.             }
  726.         }
  727.     }
  728.     /////// CRON
  729.     /**
  730.      * @Route("/confirmRdvSms", name="confirmRdvSms", methods={"GET","HEAD"})
  731.      */
  732.     public function confirmRdvSms(PublicFunction $publicFunction): Response
  733.     {
  734.         $date = new DateTime();
  735.         $minutes_to_add 30;
  736.         $date->add(new DateInterval('PT' $minutes_to_add 'M'));
  737.         $date->setTimezone(new DateTimeZone('Europe/Paris'));
  738.         $currentDate $date->format('Y-m-d H:i:00');
  739.         $toSend $this->getDoctrine()->getRepository(Rdv::class)
  740.             ->findRdvsIn10Mins($currentDate);
  741.         $entityManager $this->getDoctrine()->getManager();
  742.         $rdvResult = new ArrayCollection();
  743.         foreach ($toSend as $rdv) {
  744.             $date $rdv->getDate();
  745.             // $smsDate = $date->format('d-m-Y H:i');
  746.             //$client = $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  747.             //$sms = "Vous avez votre RDV du " . substr($smsDate, 0, 10) . " à " . substr($smsDate, 11, 15) . ", taper 1 si vous confirmer votre arrivé au centre auditif ou 2 si vous avez un empêchement.";
  748.             // // $publicFunction->sendEmail("MyAudio <noreply@myaudio.fr>", $client->getMail(), "My Audio: Testing CRON", "<p>Testing Cron.</p>");
  749.             //$response = $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $client->getPhone(), 4);
  750.             //$another_response = explode(" | ", $response);
  751.             // $idSms = trim($another_response[2]);
  752.             // $rdv->setIdSms($idSms);
  753.             //$entityManager->persist($rdv);
  754.             // $entityManager->flush();
  755.         }
  756.         return new Response(json_encode([
  757.             // "test" => $idSms,
  758.             "currentDate" => $currentDate
  759.         ]));
  760.     }
  761.     /////// CRON 
  762.     /**
  763.      * @Route("/validateRdvSms", name="validateRdvSms", methods={"GET","HEAD"})
  764.      */
  765.     public function validateRdvSms(Request $requestPublicFunction $publicFunction): Response
  766.     {
  767.         $entityManager $this->getDoctrine()->getManager();
  768.         $smsId $_GET['smsID'];
  769.         $message $_GET['message'];
  770.         $callLog $this->getDoctrine()
  771.             ->getRepository(CallLog::class)
  772.             ->findOneBy(['smsId' => $smsId]);
  773.         if ($callLog) {
  774.             $callLog->setAnsweredAt(new \DateTimeImmutable());
  775.             $interaction = new CallInteraction;
  776.             $interaction->setCallLog($callLog);
  777.             try {
  778.                 if ($message == "1") {
  779.                     $interaction->setStep('equipment_status');
  780.                     $interaction->setResponse('réponse_reçue');
  781.                     $interaction->setTimestamp(new \DateTimeImmutable());
  782.                     $interaction->setAdditionalData(['digit' => '1''status' => 'en_essai']);
  783.                     $entityManager->persist($interaction);
  784.                     $sms "Merci pour votre réponse. Nous notons que vous êtes actuellement en période d'essai. Merci et bonne journée avec MyAudio";
  785.                     $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$callLog->getPhoneNumber(), 4);
  786.                 } else if ($message == "2") {
  787.                     $interaction->setStep('equipment_status');
  788.                     $interaction->setResponse('réponse_reçue');
  789.                     $interaction->setTimestamp(new \DateTimeImmutable());
  790.                     $interaction->setAdditionalData(['digit' => '2''status' => 'finalise']);
  791.                     $entityManager->persist($interaction);
  792.                     $sms "Félicitations pour votre appareillage ! Nous sommes ravis que vous ayez finalisé cet achat important. Bonne journée avec My Audio.";
  793.                     $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$callLog->getPhoneNumber(), 4);
  794.                 } else if ($message == "3") {
  795.                     $interaction->setStep('equipment_status');
  796.                     $interaction->setResponse('réponse_reçue');
  797.                     $interaction->setTimestamp(new \DateTimeImmutable());
  798.                     $interaction->setAdditionalData(['digit' => '3''status' => 'abandonne']);
  799.                     $entityManager->persist($interaction);
  800.                     $sms "Nous avons bien noté que vous avez rendu les appareils sans finaliser l'achat. Bonne journée avec My Audio.";
  801.                     $result $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$callLog->getPhoneNumber(), 4);
  802.                     error_log("Résultat envoi SMSSSSSSSSSSSSSSSSSSSSSSSSS: " json_encode($result));
  803.                 } else if ($message == "4") {
  804.                     $interaction->setStep('equipment_status');
  805.                     $interaction->setResponse('réponse_reçue');
  806.                     $interaction->setTimestamp(new \DateTimeImmutable());
  807.                     $interaction->setAdditionalData(['digit' => '4''status' => 'attente_rdv_orl']);
  808.                     $entityManager->persist($interaction);
  809.                     $sms "Nous avons bien noté que vous etes en attente d'un rendez-vous avec un ORL. Bonne journée avec My Audio.";
  810.                     $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$callLog->getPhoneNumber(), 4);
  811.                 } else if ($message == "5") {
  812.                     $interaction->setStep('equipment_status');
  813.                     $interaction->setResponse('réponse_reçue');
  814.                     $interaction->setTimestamp(new \DateTimeImmutable());
  815.                     $interaction->setAdditionalData(['digit' => '5''status' => 'autre']);
  816.                     $entityManager->persist($interaction);
  817.                     $sms "Merci pour votre réponse. Un conseiller My Audio vous contactera dans les prochains jours. Bonne journée.";
  818.                     $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$callLog->getPhoneNumber(), 4);
  819.                 } else {
  820.                     error_log("Message non reconnu: " $message);
  821.                     return new Response(json_encode([
  822.                         "message" => "La réponse spécifiée est incorrecte",
  823.                         "status" => 401,
  824.                         "réponse" => $message,
  825.                     ]), 401);
  826.                 }
  827.                 $entityManager->flush();
  828.                 return new Response(json_encode([
  829.                     "message" => "Réponse traitée avec succès",
  830.                     "status" => 200,
  831.                 ]));
  832.             } catch (\Exception $e) {
  833.                 return new Response(json_encode([
  834.                     "message" => "Erreur lors du traitement de la réponse: " $e->getMessage(),
  835.                     "status" => 500,
  836.                 ]), 500);
  837.             }
  838.         }
  839.         return new Response(json_encode([
  840.             "smsId" => $smsId,
  841.             "message" => $currentDate
  842.         ]));
  843.     }
  844.     /**
  845.      * @Route("/rdvs/old/client/{id}", name="getOldRdvsByClientId", methods={"GET","HEAD"})
  846.      */
  847.     public function getOldRdvsByClientId(Request $requestClient $clientPublicFunction $publicFunction)
  848.     {
  849.         if (!$request->query->get('token')) {
  850.             return new Response(json_encode([
  851.                 "message" => "Pas de token n'a été spécifié",
  852.                 "status" => 401,
  853.             ]), 401);
  854.         }
  855.         $entityManager $this->getDoctrine()->getManager();
  856.         /** @var Token */
  857.         $token $this->getDoctrine()
  858.             ->getRepository(Token::class)
  859.             ->findOneBy(['token' => $request->query->get('token')]);
  860.         if (!$token) {
  861.             return new Response(json_encode([
  862.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  863.                 "status" => 404,
  864.             ]), 404);
  865.         }
  866.         // get token age
  867.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  868.         // if the token if older than 7 days
  869.         if ($dateDiff->7) {
  870.             $entityManager->remove($token);
  871.             $entityManager->flush();
  872.             return $this->json([
  873.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  874.                 'path' => 'src/Controller/ClientController.php',
  875.                 "status" => 401,
  876.             ], 401);
  877.         }
  878.         if ($token->getIdClient()) {
  879.             if ($client != $token->getIdClient()) {
  880.                 return new Response(json_encode([
  881.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  882.                     "status" => 404,
  883.                 ]), 404);
  884.             }
  885.         } else if ($token->getIdAudio()) {
  886.             /** @var Token */
  887.             $token $this->getDoctrine()
  888.                 ->getRepository(Rdv::class)
  889.                 ->findOneBy(['id_client' => $client'id_audio' => $token->getIdAudio()]);
  890.             if ($client != $token->getIdClient()) {
  891.                 return new Response(json_encode([
  892.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  893.                     "status" => 404,
  894.                 ]), 404);
  895.             }
  896.         } else {
  897.             return new Response(json_encode([
  898.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  899.                 "status" => 404,
  900.             ]), 404);
  901.         }
  902.         if ($request->query->get('audio')) {
  903.             /** @var ActivityRepository */
  904.             $activityRepo $this->getDoctrine();
  905.             if ($request->query->get('limit')) {
  906.                 /** @var Rdv[] */
  907.                 $rdvs $activityRepo
  908.                     ->getRepository(Rdv::class)
  909.                     ->findLastsOldRdvsWithLimit($request->query->get('limit'), $client->getId(), $request->query->get('audio'), new DateTime());
  910.                 $rdvResult = new ArrayCollection();
  911.             } else {
  912.                 /** @var Rdv[] */
  913.                 $rdvs $activityRepo
  914.                     ->getRepository(Rdv::class)
  915.                     ->findOldRdvs($client->getId(), $request->query->get('audio'), new DateTime());
  916.                 $rdvResult = new ArrayCollection();
  917.             }
  918.             foreach ($rdvs as $rdv) {
  919.                 /*if ($rdv->getIdEtat()->getId() != 1) {
  920.                     continue;
  921.                 }*/
  922.                 /** @var AudioMotif */
  923.                 $audioMotif $this->getDoctrine()
  924.                     ->getRepository(AudioMotif::class)
  925.                     ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  926.                 if (!$audioMotif) {
  927.                     continue;
  928.                 }
  929.                 $duration '';
  930.                 if (is_null($rdv->getDuration())) {
  931.                     $duration $audioMotif->getDuration();
  932.                 } else {
  933.                     $duration $rdv->getDuration();
  934.                 }
  935.                 $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  936.                 /** @var Rdv[] */
  937.                 $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  938.                     ->findAllReviewsCentre($rdvCentre->getId());
  939.                 $rdvItem = [
  940.                     "id" => $rdv->getId(),
  941.                     "motif_id" => $rdv->getIdMotif()->getId(),
  942.                     "duration" => $duration,
  943.                     "color" => $audioMotif->getColor(),
  944.                     "audio_id" => $rdv->getIdAudio()->getId(),
  945.                     "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  946.                     "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  947.                     "client_id" => $rdv->getIdClient()->getId(),
  948.                     "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() . " " $rdv->getIdProche()->getLastname() : $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname(),
  949.                     "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  950.                     "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  951.                     "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  952.                     "testclient" => $rdv->getTestClient() ? [
  953.                         "result" => $rdv->getTestClient()->getResultTonal(),
  954.                         "date" => $rdv->getTestClient()->getDate(),
  955.                         "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  956.                     ] : null,
  957.                     "name" => $rdvCentre->getName(),
  958.                     "phone" => $rdvCentre->getPhone(),
  959.                     "imgUrl" => $rdvCentre->getImgUrl(),
  960.                     "address" => $rdvCentre->getAddress(),
  961.                     "postale" => $rdvCentre->getPostale(),
  962.                     "city" => $rdvCentre->getCity(),
  963.                     "etat_id" => $rdvCentre->getId(),
  964.                     "averageRating" => $publicFunction->calculateRating($centreRdvs),
  965.                     "nbrReview" => count($centreRdvs),
  966.                     "acceptedCurrency" => "CB Chèque",
  967.                     "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  968.                     "note" => $rdv->getNote(),
  969.                     "comment" => $rdv->getComment(),
  970.                     "review" => $rdv->getReview(),
  971.                 ];
  972.                 $rdvResult->add($rdvItem);
  973.             }
  974.         }
  975.         if (count($rdvResult) > 0) {
  976.             return new Response(json_encode(([
  977.                 "rdv" => $rdvResult->toArray(),
  978.                 "status" => 200,
  979.             ])));
  980.         } else {
  981.             return new Response(json_encode(([
  982.                 "message" => "Aucun rendez-vous a venir!",
  983.                 'path' => 'src/Controller/RdvController.php',
  984.                 "status" => 404,
  985.             ])));
  986.         }
  987.     }
  988.     /**
  989.      * @Route("/rdvs/old/client/{id}/centre", name="getOldRdvsByClientIdForCentre", methods={"GET","HEAD"})
  990.      */
  991.     public function getOldRdvsByClientIdForCentre(Request $requestClient $clientPublicFunction $publicFunction)
  992.     {
  993.         if (!$request->query->get('token')) {
  994.             return new Response(json_encode([
  995.                 "message" => "Pas de token n'a été spécifié",
  996.                 "status" => 401,
  997.             ]), 401);
  998.         }
  999.         $entityManager $this->getDoctrine()->getManager();
  1000.         /** @var Token */
  1001.         $token $this->getDoctrine()
  1002.             ->getRepository(Token::class)
  1003.             ->findOneBy(['token' => $request->query->get('token')]);
  1004.         if (!$token) {
  1005.             return new Response(json_encode([
  1006.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1007.                 "status" => 404,
  1008.             ]), 404);
  1009.         }
  1010.         $audio $this->getDoctrine()
  1011.             ->getRepository(Audio::class)
  1012.             ->findOneBy(['id' => $request->query->get('audio')]);
  1013.         $audioCentre $this->getDoctrine()
  1014.             ->getRepository(AudioCentre::class)
  1015.             ->findOneBy(['id_audio' => $audio]);
  1016.         // get token age
  1017.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1018.         // if the token if older than 7 days
  1019.         if ($dateDiff->7) {
  1020.             $entityManager->remove($token);
  1021.             $entityManager->flush();
  1022.             return $this->json([
  1023.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1024.                 'path' => 'src/Controller/ClientController.php',
  1025.                 "status" => 401,
  1026.             ], 401);
  1027.         }
  1028.         if ($token->getIdClient()) {
  1029.             if ($client != $token->getIdClient()) {
  1030.                 return new Response(json_encode([
  1031.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  1032.                     "status" => 404,
  1033.                 ]), 404);
  1034.             }
  1035.         } else if ($token->getIdAudio()) {
  1036.             /** @var Token */
  1037.             if ($token->getIdAudio() != $audio) {
  1038.                 return new Response(json_encode([
  1039.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  1040.                     "status" => 404,
  1041.                 ]), 404);
  1042.             }
  1043.         } else {
  1044.             return new Response(json_encode([
  1045.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  1046.                 "status" => 404,
  1047.             ]), 404);
  1048.         }
  1049.         if ($request->query->get('audio')) {
  1050.             /** @var ActivityRepository */
  1051.             $activityRepo $this->getDoctrine();
  1052.             if ($request->query->get('limit')) {
  1053.                 /** @var Rdv[] */
  1054.                 $rdvs $activityRepo
  1055.                     ->getRepository(Rdv::class)
  1056.                     ->findLastsOldRdvCentresWithLimit($request->query->get('limit'), $client->getId(), $audioCentre->getIdCentre()->getId(), new DateTime());
  1057.                 $rdvResult = new ArrayCollection();
  1058.             } else {
  1059.                 /** @var Rdv[] */
  1060.                 $rdvs $activityRepo
  1061.                     ->getRepository(Rdv::class)
  1062.                     ->findOldRdvsByCentre($client->getId(), $audioCentre->getIdCentre()->getId(), new DateTime());
  1063.                 $rdvResult = new ArrayCollection();
  1064.             }
  1065.             //dd($rdvs);
  1066.             foreach ($rdvs as $rdv) {
  1067.                 // we comment this becoz it was just the validate , we implment other choice select
  1068.                 /* if ($rdv->getIdEtat()->getId() != 5) {
  1069.                     continue;
  1070.                 }*/
  1071.                 /** @var AudioMotif */
  1072.                 $audioMotif $this->getDoctrine()
  1073.                     ->getRepository(AudioMotif::class)
  1074.                     ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  1075.                 if (!$audioMotif) {
  1076.                     continue;
  1077.                 }
  1078.                 $duration '';
  1079.                 if (is_null($rdv->getDuration())) {
  1080.                     $duration $audioMotif->getDuration();
  1081.                 } else {
  1082.                     $duration $rdv->getDuration();
  1083.                 }
  1084.                 $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  1085.                 /** @var Rdv[] */
  1086.                 $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  1087.                     ->findAllReviewsCentre($rdvCentre->getId());
  1088.                 $rdvItem = [
  1089.                     "id" => $rdv->getId(),
  1090.                     "motif_id" => $rdv->getIdMotif()->getId(),
  1091.                     "duration" => $duration,
  1092.                     "color" => $audioMotif->getColor(),
  1093.                     "audio_id" => $rdv->getIdAudio()->getId(),
  1094.                     "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  1095.                     "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  1096.                     "client_id" => $rdv->getIdClient()->getId(),
  1097.                     "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() . " " $rdv->getIdProche()->getLastname() : $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname(),
  1098.                     "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  1099.                     "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  1100.                     "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  1101.                     "testclient" => $rdv->getTestClient() ? [
  1102.                         "result" => $rdv->getTestClient()->getResultTonal(),
  1103.                         "date" => $rdv->getTestClient()->getDate(),
  1104.                         "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  1105.                     ] : null,
  1106.                     "name" => $rdvCentre->getName(),
  1107.                     "phone" => $rdvCentre->getPhone(),
  1108.                     "imgUrl" => $rdvCentre->getImgUrl(),
  1109.                     "address" => $rdvCentre->getAddress(),
  1110.                     "postale" => $rdvCentre->getPostale(),
  1111.                     "city" => $rdvCentre->getCity(),
  1112.                     "etat_id" => $rdvCentre->getId(),
  1113.                     "averageRating" => $publicFunction->calculateRating($centreRdvs),
  1114.                     "nbrReview" => count($centreRdvs),
  1115.                     "acceptedCurrency" => "CB Chèque",
  1116.                     "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  1117.                     "note" => $rdv->getNote(),
  1118.                     "comment" => $rdv->getComment(),
  1119.                     "review" => $rdv->getReview(),
  1120.                     "status" => $rdv->getIdEtat()->getLibelle()
  1121.                 ];
  1122.                 $rdvResult->add($rdvItem);
  1123.             }
  1124.         }
  1125.         if (count($rdvResult) > 0) {
  1126.             return new Response(json_encode(([
  1127.                 "rdv" => $rdvResult->toArray(),
  1128.                 "status" => 200,
  1129.             ])));
  1130.         } else {
  1131.             return new Response(json_encode(([
  1132.                 "message" => "Aucun rendez-vous n'a été trouvé!",
  1133.                 'path' => 'src/Controller/RdvController.php',
  1134.                 "status" => 404,
  1135.             ])));
  1136.         }
  1137.     }
  1138.     private function getOpeningHours($centerId)
  1139.     {
  1140.         $center $this->getDoctrine()->getRepository(Centre::class)->find($centerId);
  1141.         $audioCentre $this->getDoctrine()->getRepository(AudioCentre::class)
  1142.             ->findOneBy(['id_centre' => $center->getId(), 'id_audio' => $center->getIdGerant()->getId()]);
  1143.         $schedule $audioCentre->getHoraire();
  1144.         $availableHours = [];
  1145.         if (isset($schedule['fixed'])) {
  1146.             foreach ($schedule['fixed'] as $day => $hours) {
  1147.                 $dayInFrench strtolower($day);
  1148.                 $slots = [];
  1149.                 foreach ($hours as $period) {
  1150.                     $start strtotime($period['open']);
  1151.                     $end strtotime($period['close']);
  1152.                     while ($start $end) {
  1153.                         $slots[] = date('H:i'$start);
  1154.                         $start strtotime('+30 minutes'$start);
  1155.                     }
  1156.                 }
  1157.                 $availableHours[$dayInFrench] = $slots;
  1158.             }
  1159.         }
  1160.         if (isset($schedule['exceptionalOpened'])) {
  1161.             foreach ($schedule['exceptionalOpened'] as $exception) {
  1162.                 $dayOfWeek strtolower(date('l'strtotime($exception['open'])));
  1163.                 $start strtotime($exception['open']);
  1164.                 $end strtotime($exception['close']);
  1165.                 $exceptionSlots = [];
  1166.                 while ($start $end) {
  1167.                     $exceptionSlots[] = date('H:i'$start);
  1168.                     $start strtotime('+30 minutes'$start);
  1169.                 }
  1170.                 $availableHours[$dayOfWeek] = array_merge(
  1171.                     $availableHours[$dayOfWeek] ?? [],
  1172.                     $exceptionSlots
  1173.                 );
  1174.             }
  1175.         }
  1176.         if (isset($schedule['exceptionalClosed'])) {
  1177.             foreach ($schedule['exceptionalClosed'] as $exception) {
  1178.                 $dayOfWeek strtolower(date('l'strtotime($exception['open'])));
  1179.                 unset($availableHours[$dayOfWeek]);
  1180.             }
  1181.         }
  1182.         return $availableHours;
  1183.     }
  1184.     private function getBookedSlotsForDate($centerId$date)
  1185.     {
  1186.         $bookedSlots $this->getDoctrine()
  1187.             ->getRepository(Rdv::class)
  1188.             ->getBookedSlotsForDate($centerId$date);
  1189.         return $bookedSlots;
  1190.     }
  1191.     private function getAvailableSlotsForDate($openingHours$centerId$date)
  1192.     {
  1193.         $dayOfWeek date('l'strtotime($date));
  1194.         $dayInFrench $this->convertDayToFrench($dayOfWeek);
  1195.         if (!$dayInFrench) {
  1196.             throw new \Exception("Invalid day of the week: $dayOfWeek");
  1197.         }
  1198.         $slots $openingHours[$dayInFrench] ?? [];
  1199.         $bookedSlots $this->getBookedSlotsForDate($centerId$date);
  1200.         $bookedTimes = [];
  1201.         foreach ($bookedSlots as $bookedSlot) {
  1202.             $startTime $bookedSlot['date'];
  1203.             $duration $bookedSlot['duration'];
  1204.             $endTime = (clone $startTime)->modify("+$duration minutes");
  1205.             $bookedTimes[] = ['start' => $startTime'end' => $endTime];
  1206.         }
  1207.         $availableSlots = [];
  1208.         foreach ($slots as $slot) {
  1209.             $slotTime \DateTime::createFromFormat('H:i'$slot);
  1210.             $slotTime->setDate(date('Y'strtotime($date)), date('m'strtotime($date)), date('d'strtotime($date)));
  1211.             if (!$slotTime) {
  1212.                 continue;
  1213.             }
  1214.             $isAvailable true;
  1215.             foreach ($bookedTimes as $bookedTime) {
  1216.                 if ($slotTime >= $bookedTime['start'] && $slotTime $bookedTime['end']) {
  1217.                     $isAvailable false;
  1218.                     break;
  1219.                 }
  1220.             }
  1221.             if ($isAvailable) {
  1222.                 $availableSlots[] = $slot;
  1223.             }
  1224.         }
  1225.         return $availableSlots;
  1226.     }
  1227.     private function convertDayToFrench($englishDay)
  1228.     {
  1229.         $daysMap = [
  1230.             'monday' => 'lundi',
  1231.             'tuesday' => 'mardi',
  1232.             'wednesday' => 'mercredi',
  1233.             'thursday' => 'jeudi',
  1234.             'friday' => 'vendredi',
  1235.             'saturday' => 'samedi',
  1236.             'sunday' => 'dimanche'
  1237.         ];
  1238.         return $daysMap[strtolower($englishDay)] ?? null;
  1239.     }
  1240.     /**
  1241.      * @Route("/audio/{id}/rdvs/", name="getAudioRdvs", methods={"GET","HEAD"})
  1242.      */
  1243.     public function getAudioRdvs(Request $requestAudio $audio)
  1244.     {
  1245.         if (!$request->query->get('token')) {
  1246.             return new Response(json_encode([
  1247.                 "message" => "Pas de token n'a été spécifié",
  1248.                 "status" => 401,
  1249.             ]), 401);
  1250.         }
  1251.         $entityManager $this->getDoctrine()->getManager();
  1252.         /** @var Token */
  1253.         $token $this->getDoctrine()
  1254.             ->getRepository(Token::class)
  1255.             ->findOneBy(['token' => $request->query->get('token')]);
  1256.         if (!$token) {
  1257.             return new Response(json_encode([
  1258.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1259.                 "status" => 404,
  1260.             ]), 404);
  1261.         }
  1262.         // get token age
  1263.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1264.         // if the token if older than 7 days
  1265.         if ($dateDiff->7) {
  1266.             $entityManager->remove($token);
  1267.             $entityManager->flush();
  1268.             return $this->json([
  1269.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1270.                 'path' => 'src/Controller/ClientController.php',
  1271.                 "status" => 401,
  1272.             ], 401);
  1273.         }
  1274.         if ($audio != $token->getIdAudio()) {
  1275.             return new Response(json_encode([
  1276.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  1277.                 "status" => 404,
  1278.             ]), 404);
  1279.         }
  1280.         $centre = (int)$request->query->get('centre');
  1281.         if (($request->query->get('debut')) && ($request->query->get('fin'))) {
  1282.             $rdvs $this->getDoctrine()
  1283.                 ->getRepository(Rdv::class)
  1284.                 ->findBetweenDate(
  1285.                     $audio->getId(),
  1286.                     new DateTime($request->query->get('debut')),
  1287.                     new DateTime($request->query->get('fin')),
  1288.                     $centre // Le centre est maintenant un entier
  1289.                 );
  1290.         } else {
  1291.             $rdvs $this->getDoctrine()
  1292.                 ->getRepository(Rdv::class)
  1293.                 ->findBy(['id_audio' => $audio->getId()]);
  1294.         }
  1295.         $rdvResult = new ArrayCollection();
  1296.         $centerId $request->query->get('centre');
  1297.         // $openingHours = $this->getOpeningHours($centerId); 
  1298.         $centerId $request->query->get('centre');
  1299.         $dateCache = new \DateTime();
  1300.         $openingHours $this->cache->get('centre_' $centerId '_horaires_' $dateCache->format('Y-m-d'), function (ItemInterface $item) use ($centerId$dateCache) {
  1301.             $item->expiresAfter(7200);
  1302.             return $this->getOpeningHours($centerId);
  1303.         });
  1304.         //dd($openingHours);
  1305.         foreach ($rdvs as $rdv) {
  1306.             if ($rdv->getIdEtat()->getId() != null) {
  1307.                 if ($rdv->getIsAbsence() != 1) {
  1308.                     /** @var AudioMotif */
  1309.                     $audioMotif $this->getDoctrine()
  1310.                         ->getRepository(AudioMotif::class)
  1311.                         ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $audio->getId()]);
  1312.                     if (!isset($audioMotif)) {
  1313.                         continue;
  1314.                     }
  1315.                     $motif $this->getDoctrine()
  1316.                         ->getRepository(Motif::class)
  1317.                         ->findOneBy(['id' => $rdv->getIdMotif()->getId()]);
  1318.                     $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  1319.                     if ($rdv->getIdClientTemp()) {
  1320.                         $confiance "";
  1321.                     } else {
  1322.                         $confiance $client->getIdPersonneConfiance() ? $client->getIdPersonneConfiance()->getId() : null;
  1323.                     }
  1324.                 }
  1325.                 $duration '';
  1326.                 if (is_null($rdv->getDuration())) {
  1327.                     $duration $audioMotif->getDuration();
  1328.                 } else {
  1329.                     $duration $rdv->getDuration();
  1330.                 }
  1331.                 $dateFin = new DateTime($rdv->getDate()->format('Y-m-d\TH:i:s'));
  1332.                 $dateFin $dateFin->add(new DateInterval("PT" $duration "M"));
  1333.                 if ($rdv->getIdClientTemp()) {
  1334.                     $findNextRdv $this->getDoctrine()
  1335.                         ->getRepository(Rdv::class)
  1336.                         ->findBy([
  1337.                             "id_client_temp" => $rdv->getIdClientTemp(),
  1338.                             "id_motif" => ['106''107''108''109']
  1339.                         ]);
  1340.                 } else {
  1341.                     $findNextRdv $this->getDoctrine()
  1342.                         ->getRepository(Rdv::class)
  1343.                         ->findBy([
  1344.                             "id_client_temp" => $rdv->getIdClient(),
  1345.                             "id_motif" => ['106''107''108''109']
  1346.                         ]);
  1347.                 }
  1348.                 $finalRdv null;
  1349.                 /*if ($rdv->getRdvParent()) {
  1350.     $finalRdv = $this->getDoctrine()
  1351.         ->getRepository(Rdv::class)
  1352.         ->find($rdv->getRdvParent());
  1353. }*/
  1354.                 //if($client->getClientDevices())
  1355.                 //{
  1356.                 //if ($client->getClientDevices()->first()) {
  1357.                 /*$nextRdv = $this->getDoctrine()
  1358.                  ->getRepository(Rdv::class)
  1359.                  ->find($finalRdv->getClientDevice()->getRdv()->getId());*/
  1360.                 //  }
  1361.                 //}
  1362.                 if ($rdv->getIsAbsence() != 1) {
  1363.                     if ($rdv->getIdClientTemp()) {
  1364.                         $nextRdvs $this->getDoctrine()
  1365.                             ->getRepository(Rdv::class)
  1366.                             ->findBy([
  1367.                                 "id_client_temp" => $client,
  1368.                                 "id_motif" => ['106''107''108''109']
  1369.                             ]);
  1370.                     } else {
  1371.                         $nextRdvs $this->getDoctrine()
  1372.                             ->getRepository(Rdv::class)
  1373.                             ->findBy([
  1374.                                 "id_client" => $client,
  1375.                                 "id_motif" => ['106''107''108''109']
  1376.                             ]);
  1377.                     }
  1378.                     if ($client->getClientDevices()) {
  1379.                         if ($client->getClientDevices()->first()) {
  1380.                             if (empty($nextRdvs)) {
  1381.                                 $isNextRdv false;
  1382.                                 $initialRdvDate $rdv->getDate();
  1383.                                 $availableSlots = [
  1384.                                     'Suivi de l’essai' => $this->findFirstAvailableSlot($centerId$initialRdvDate7),
  1385.                                     'Confirmation de l’essai' => $this->findFirstAvailableSlot($centerId$initialRdvDate14),
  1386.                                     'Validation de l’appareillage' => $this->findFirstAvailableSlot($centerId$initialRdvDate21),
  1387.                                     'Facturation de l’appareillage' => $this->findFirstAvailableSlot($centerId$initialRdvDate30),
  1388.                                     'duration' => "30"
  1389.                                 ];
  1390.                                 $mappedNextRdvs = [
  1391.                                     'Suivi de l’essai' => $this->findAvailableDay($centerId$initialRdvDate7),
  1392.                                     'Confirmation de l’essai' => $this->findAvailableDay($centerId$initialRdvDate14),
  1393.                                     'Validation de l’appareillage' => $this->findAvailableDay($centerId$initialRdvDate21),
  1394.                                     'Facturation de l’appareillage' => $this->findAvailableDay($centerId$initialRdvDate30),
  1395.                                     'duration' => "30"
  1396.                                 ];
  1397.                             } else {
  1398.                                 $isNextRdv true;
  1399.                                 $initialRdvDate $rdv->getDate();
  1400.                                 // Available slots for each follow-up date
  1401.                                 $availableSlots = [];
  1402.                                 if (isset($nextRdvs[0])) {
  1403.                                     $availableSlots['Suivi de l’essai'] = $this->getAvailableSlotsForDate(
  1404.                                         $openingHours,
  1405.                                         $centerId,
  1406.                                         $nextRdvs[0]->getDate()->format('Y-m-d')
  1407.                                     );
  1408.                                 }
  1409.                                 if (isset($nextRdvs[1])) {
  1410.                                     $availableSlots['Confirmation de l’essai'] = $this->getAvailableSlotsForDate(
  1411.                                         $openingHours,
  1412.                                         $centerId,
  1413.                                         $nextRdvs[1]->getDate()->format('Y-m-d')
  1414.                                     );
  1415.                                 }
  1416.                                 if (isset($nextRdvs[2])) {
  1417.                                     $availableSlots['Validation de l’appareillage'] = $this->getAvailableSlotsForDate(
  1418.                                         $openingHours,
  1419.                                         $centerId,
  1420.                                         $nextRdvs[2]->getDate()->format('Y-m-d')
  1421.                                     );
  1422.                                 }
  1423.                                 if (isset($nextRdvs[3])) {
  1424.                                     $availableSlots['Facturation de l’appareillage'] = $this->getAvailableSlotsForDate(
  1425.                                         $openingHours,
  1426.                                         $centerId,
  1427.                                         $nextRdvs[3]->getDate()->format('Y-m-d')
  1428.                                     );
  1429.                                 }
  1430.                                 $mappedNextRdvs array_map(function ($rdv) {
  1431.                                     return [
  1432.                                         'id' => $rdv->getId(),
  1433.                                         'date' => $rdv->getDate()->format('d-m-Y'),
  1434.                                         'hours' => $rdv->getDate()->format('H:i'),
  1435.                                         'duration' => $rdv->getDuration(),
  1436.                                         "motif_id" => $rdv->getIdMotif()->getId(),
  1437.                                         "motif_titre" => $rdv->getIdMotif()->getTitre(),
  1438.                                     ];
  1439.                                 }, $nextRdvs);
  1440.                             }
  1441.                         }
  1442.                     }
  1443.                     $rdvItem = [
  1444.                         "id" => $rdv->getId(),
  1445.                         "motif_id" => $rdv->getIdMotif()->getId(),
  1446.                         "motif_titre" => $motif->getTitre(),
  1447.                         "duration" => $duration,
  1448.                         "color" => $audioMotif->getColor(),
  1449.                         "audio_id" => $rdv->getIdAudio()->getId(),
  1450.                         "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  1451.                         "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  1452.                         "client_id" => $client->getId(),
  1453.                         "isClient" => ($client instanceof Client) ? 0,
  1454.                         "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() : $client->getName(),
  1455.                         "client_lastname" => $rdv->getIdProche() ? $rdv->getIdProche()->getLastname() : $client->getLastname(),
  1456.                         "client_mail" => $client->getMail(),
  1457.                         "client_tel" => $client->getPhone(),
  1458.                         "client_fixe" => $client->getPhoneFixe(),
  1459.                         "confiance" =>  $confiance,
  1460.                         "client_birthday" => $client->getBirthdate() ? $client->getBirthdate()->format("Y-m-d") : null,
  1461.                         "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  1462.                         "centre_id" => $rdv->getIdCentre()->getId(),
  1463.                         "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  1464.                         "testclient" => $rdv->getTestClient() ? [
  1465.                             "result" => $rdv->getTestClient()->getResultTonal(),
  1466.                             "date" => $rdv->getTestClient()->getDate(),
  1467.                             "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  1468.                         ] : null,
  1469.                         "name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : $rdv->getIdLieu()->getName(),
  1470.                         "centerName" => $rdv->getIdCentre()->getName(),
  1471.                         "phone" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getPhone() : $rdv->getIdLieu()->getPhone(),
  1472.                         "etat_id" => $rdv->getIdEtat()->getId(),
  1473.                         "clientEtatId" => $client->getClientStatus() ? $client->getClientStatus()->getId() : 0,
  1474.                         "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  1475.                         "dateFin" => $dateFin->format('Y-m-d\TH:i:s'),
  1476.                         "comment" => $rdv->getComment(),
  1477.                         "note" => $rdv->getNote(),
  1478.                         "isTemp" => $rdv->getIdClientTemp() ? 0,
  1479.                         "isAbsence" => $rdv->getIsAbsence(),
  1480.                         "device" => $client->getClientDevices()->first() ? [
  1481.                             "isDevice" => true,
  1482.                             "isNextRdv" => $isNextRdv,
  1483.                             "deviceID" => $client->getClientDevices()->first()->getDevice()->getId(),
  1484.                             "clientDeviceID" => $client->getClientDevices()->first()->getId(),
  1485.                             "deviceModel" => $client->getClientDevices()->first()->getDevice()->getModel(),
  1486.                             "settingDeviceId" => $client->getClientDevices()->first()->getSettingDevice()->getSlug(),
  1487.                             "settingName" => $client->getClientDevices()->first()->getSettingDevice()->getName(),
  1488.                             "settingSlug" => $client->getClientDevices()->first()->getSettingDevice()->getSlug(),
  1489.                             "nextRdvs" => $mappedNextRdvs,
  1490.                             "available_slots" => $availableSlots
  1491.                         ] : [
  1492.                             "isDevice" => false
  1493.                         ]
  1494.                     ];
  1495.                 } else {
  1496.                     // $clientDevice = $client->getClientDevices()->first();
  1497.                     $rdvItem = [
  1498.                         "id" => $rdv->getId(),
  1499.                         "duration" => $duration,
  1500.                         "color" => $rdv->getColor() ? $rdv->getColor() . '66' '#ffb2b266',
  1501.                         "audio_id" => $rdv->getIdAudio()->getId(),
  1502.                         "client_id" =>  "",
  1503.                         "isClient" => false,
  1504.                         "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  1505.                         "centre_id" => $rdv->getIdCentre()->getId(),
  1506.                         "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  1507.                         "name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : $rdv->getIdLieu()->getName(),
  1508.                         "phone" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getPhone() : $rdv->getIdLieu()->getPhone(),
  1509.                         "etat_id" => $rdv->getIdEtat()->getId(),
  1510.                         "clientEtatId" => "",
  1511.                         "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  1512.                         "dateFin" => $dateFin->format('Y-m-d\TH:i:s'),
  1513.                         "note" => $rdv->getNote(),
  1514.                         "device" => "",
  1515.                         "centerName" => $rdv->getIdCentre()->getName(),
  1516.                         "isTemp" => $rdv->getIdClientTemp() ? 0,
  1517.                         "isAbsence" => $rdv->getIsAbsence(),
  1518.                         "motif_titre" => $rdv->getMotifAbsence() ? $rdv->getMotifAbsence() : "Absence",
  1519.                     ];
  1520.                 }
  1521.                 //  if ($rdv->getDate() >= new DateTime())
  1522.                 $rdvResult->add($rdvItem);
  1523.             }
  1524.         }
  1525.         $startDate = new \DateTime('2024-02-20');
  1526.         $rdvs $this->rdvRepo->findRdvsNeedingReminderByAudio($startDate$audio->getId());
  1527.         //dd($audio->getId());
  1528.         $reminders = [];
  1529.         //dd($rdvs);
  1530.         foreach ($rdvs as $rdv) {
  1531.             $info $this->checkRdvReminder($rdv);
  1532.             if ($info !== null) {
  1533.                 $reminders[] = $info;
  1534.             }
  1535.         }
  1536.         //dd($reminders);
  1537.         if (count($rdvResult) > 0) {
  1538.             return new Response(json_encode(([
  1539.                 "content" => $rdvResult->toArray(),
  1540.                 "status" => 200,
  1541.                 "reminders" => $reminders,
  1542.                 "datefin" => $dateFin
  1543.             ])));
  1544.         } else {
  1545.             $rdvItem = [];
  1546.             //$rdvResult->add($rdvItem);
  1547.             return new Response(json_encode(([
  1548.                 "content" => $rdvResult->toArray(),
  1549.                 "message" => "Aucun rendez-vous n'a été trouvé!",
  1550.                 'path' => 'src/Controller/RdvController.php',
  1551.                 "reminders" => $reminders,
  1552.                 "status" => 404,
  1553.             ])));
  1554.         }
  1555.     }
  1556.     private function findAvailableDay(int $centerId\DateTime $initialRdvDateint $offset): string
  1557.     {
  1558.         $currentDate = (clone $initialRdvDate)->modify("+{$offset} days");
  1559.         while (true) {
  1560.             $formattedDate $currentDate->format('Y-m-d');
  1561.             $slots $this->getAvailableSlotsForDate(
  1562.                 $this->getOpeningHoursList($centerId$formattedDate),
  1563.                 $centerId,
  1564.                 $formattedDate
  1565.             );
  1566.             if (!empty($slots)) {
  1567.                 return $formattedDate;
  1568.             }
  1569.             $currentDate->modify('+1 day');
  1570.         }
  1571.     }
  1572.     private function findFirstAvailableSlot(int $centerId\DateTime $initialRdvDateint $offset): array
  1573.     {
  1574.         $currentDate = (clone $initialRdvDate)->modify("+{$offset} days");
  1575.         while (true) {
  1576.             $formattedDate $currentDate->format('Y-m-d');
  1577.             $slots $this->getAvailableSlotsForDate(
  1578.                 $this->getOpeningHoursList($centerId$formattedDate),
  1579.                 $centerId,
  1580.                 $formattedDate
  1581.             );
  1582.             if (!empty($slots)) {
  1583.                 return $slots;
  1584.             }
  1585.             $currentDate->modify('+1 day');
  1586.         }
  1587.     }
  1588.     private function getOpeningHoursList($centerId$date)
  1589.     {
  1590.         $center $this->getDoctrine()->getRepository(Centre::class)->find($centerId);
  1591.         $audioCentre $this->getDoctrine()->getRepository(AudioCentre::class)
  1592.             ->findOneBy(['id_centre' => $center->getId(), 'id_audio' => $center->getIdGerant()->getId()]);
  1593.         $schedule $audioCentre->getHoraire();
  1594.         $availableHours = [];
  1595.         $holidayDates = [
  1596.             'JourdelAn' => '01-01',
  1597.             'LundidePâques' => '21-04',
  1598.             'FêteduTravail' => '01-05',
  1599.             'Victoire1945' => '08-05',
  1600.             'Ascension' => '29-05',
  1601.             'LundidePentecôte' => '09-06',
  1602.             'FêteNationale' => '14-07',
  1603.             'Assomption' => '15-08',
  1604.             'Toussaint' => '01-11',
  1605.             'Armistice1918' => '11-11',
  1606.             'Noël' => '25-12',
  1607.         ];
  1608.         $holidays $center->getHorairesHoliday();
  1609.         $requestDate date('d-m'strtotime($date));
  1610.         $englishToFrenchDays = [
  1611.             'monday' => 'lundi',
  1612.             'tuesday' => 'mardi',
  1613.             'wednesday' => 'mercredi',
  1614.             'thursday' => 'jeudi',
  1615.             'friday' => 'vendredi',
  1616.             'saturday' => 'samedi',
  1617.             'sunday' => 'dimanche',
  1618.         ];
  1619.         $dayOfWeek strtolower(date('l'strtotime($date)));
  1620.         $dayInFrench $englishToFrenchDays[$dayOfWeek];
  1621.         if (isset($schedule['fixed'])) {
  1622.             foreach ($schedule['fixed'] as $day => $hours) {
  1623.                 $dayKey strtolower($day);
  1624.                 $slots = [];
  1625.                 foreach ($hours as $period) {
  1626.                     $start strtotime($period['open']);
  1627.                     $end strtotime($period['close']);
  1628.                     while ($start $end) {
  1629.                         $slots[] = date('H:i'$start);
  1630.                         $start strtotime('+30 minutes'$start);
  1631.                     }
  1632.                 }
  1633.                 $availableHours[$dayKey] = $slots;
  1634.             }
  1635.         }
  1636.         foreach ($holidays['fixed'] as $holiday => $hours) {
  1637.             if (isset($holidayDates[$holiday]) && $holidayDates[$holiday] === $requestDate) {
  1638.                 $holidaySlots = [];
  1639.                 if (!empty($hours)) {
  1640.                     foreach ($hours as $period) {
  1641.                         $start strtotime($period['open']);
  1642.                         $end strtotime($period['close']);
  1643.                         while ($start $end) {
  1644.                             $holidaySlots[] = date('H:i'$start);
  1645.                             $start strtotime('+30 minutes'$start);
  1646.                         }
  1647.                     }
  1648.                     $availableHours[$dayInFrench] = $holidaySlots;
  1649.                 } else {
  1650.                     $availableHours[$dayInFrench] = [];
  1651.                 }
  1652.                 break;
  1653.             }
  1654.         }
  1655.         return $availableHours;
  1656.     }
  1657.     /**
  1658.      * @Route("/audio/{id}/rdvsTest/", name="getAudioRdvsTest", methods={"GET","HEAD"})
  1659.      */
  1660.     public function getAudioRdvsTest(Request $requestAudio $audio)
  1661.     {
  1662.         if (!$request->query->get('token')) {
  1663.             return new Response(json_encode([
  1664.                 "message" => "Pas de token n'a été spécifié",
  1665.                 "status" => 401,
  1666.             ]), 401);
  1667.         }
  1668.         $entityManager $this->getDoctrine()->getManager();
  1669.         /** @var Token */
  1670.         $token $this->getDoctrine()
  1671.             ->getRepository(Token::class)
  1672.             ->findOneBy(['token' => $request->query->get('token')]);
  1673.         if (!$token) {
  1674.             return new Response(json_encode([
  1675.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1676.                 "status" => 404,
  1677.             ]), 404);
  1678.         }
  1679.         // get token age
  1680.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1681.         // if the token if older than 7 days
  1682.         if ($dateDiff->7) {
  1683.             $entityManager->remove($token);
  1684.             $entityManager->flush();
  1685.             return $this->json([
  1686.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1687.                 'path' => 'src/Controller/ClientController.php',
  1688.                 "status" => 401,
  1689.             ], 401);
  1690.         }
  1691.         if ($audio != $token->getIdAudio()) {
  1692.             return new Response(json_encode([
  1693.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  1694.                 "status" => 404,
  1695.             ]), 404);
  1696.         }
  1697.         /** @var Rdv[] */
  1698.         if (($request->query->get('debut')) && ($request->query->get('fin'))) {
  1699.             $rdvs $this->getDoctrine()
  1700.                 ->getRepository(Rdv::class)
  1701.                 ->findBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1702.         } else {
  1703.             $rdvs $this->getDoctrine()
  1704.                 ->getRepository(Rdv::class)
  1705.                 ->findBy(['id_audio' => $audio->getId()]);
  1706.         }
  1707.         $rdvResult = new ArrayCollection();
  1708.         foreach ($rdvs as $rdv) {
  1709.             if ($rdv->getIdEtat()->getId() != null) {
  1710.                 /** @var AudioMotif */
  1711.                 $audioMotif $this->getDoctrine()
  1712.                     ->getRepository(AudioMotif::class)
  1713.                     ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $audio->getId()]);
  1714.                 if (!isset($audioMotif)) {
  1715.                     continue;
  1716.                 }
  1717.                 $motif $this->getDoctrine()
  1718.                     ->getRepository(Motif::class)
  1719.                     ->findOneBy(['id' => $rdv->getIdMotif()->getId()]);
  1720.                 $dateFin = new DateTime($rdv->getDate()->format('Y-m-d H:i:s'));
  1721.                 $dateFin $dateFin->add(new DateInterval("PT" $audioMotif->getDuration() . "M"));
  1722.                 $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  1723.                 $name $rdv->getIdProche() ? $rdv->getIdProche()->getName() : $client->getName();
  1724.                 $lastName $rdv->getIdProche() ? $rdv->getIdProche()->getLastname() : $client->getLastname();
  1725.                 $rdvItem = [
  1726.                     "id" => $rdv->getId(),
  1727.                     "title" => $lastName ' ' $name,
  1728.                     "start" => $rdv->getDate()->format('Y-m-d H:i:s'),
  1729.                     "end"   => $dateFin->format('Y-m-d H:i:s'),
  1730.                     "backgroundColor" => $audioMotif->getColor(),
  1731.                     "editable" => true,
  1732.                     "durationEditable" => false,
  1733.                     "resourceEditable" => true,
  1734.                     "cache" => false,
  1735.                     "motif_id" => $rdv->getIdMotif()->getId(),
  1736.                     "motif" => $motif->getTitre(),
  1737.                     "duree" => $audioMotif->getDuration(),
  1738.                     "color" => $audioMotif->getColor(),
  1739.                     "color_motif" => $audioMotif->getColor(),
  1740.                     "client_id" => $client->getId(),
  1741.                     "clientName" => $name,
  1742.                     "clientLastName" => $lastName,
  1743.                     "mail" => $client->getMail(),
  1744.                     "telephone" => $client->getPhone(),
  1745.                     "birthday" => $client->getBirthdate(),
  1746.                     "etat_id" => $rdv->getIdEtat()->getId(),
  1747.                     "dateDeb" => $rdv->getDate()->format('Y-m-d H:i:s'),
  1748.                     "dateFin" => $dateFin->format('Y-m-d H:i:s'),
  1749.                     "commentaire" => $rdv->getNote(),
  1750.                     "event_title" => "<b>" $lastName "</b> " $name,
  1751.                 ];
  1752.                 //  if ($rdv->getDate() >= new DateTime())
  1753.                 $rdvResult->add($rdvItem);
  1754.             }
  1755.         }
  1756.         if (count($rdvResult) > 0) {
  1757.             return new Response(json_encode(
  1758.                 $rdvResult->toArray(),
  1759.             ));
  1760.         } else {
  1761.             $rdvItem = [];
  1762.             //$rdvResult->add($rdvItem);
  1763.             return new Response(json_encode(
  1764.                 $rdvResult->toArray(),
  1765.             ));
  1766.         }
  1767.     }
  1768.     /**
  1769.      * @Route("/audio/{id}/rdvs/count", name="getCountAudioRdvs", methods={"GET","HEAD"})
  1770.      */
  1771.     public function getCountAudioRdvs(Request $requestAudio $audio)
  1772.     {
  1773.         if (!$request->query->get('token')) {
  1774.             return new Response(json_encode([
  1775.                 "message" => "Pas de token n'a été spécifié",
  1776.                 "status" => 401,
  1777.             ]), 401);
  1778.         }
  1779.         $entityManager $this->getDoctrine()->getManager();
  1780.         /** @var Token */
  1781.         $token $this->getDoctrine()
  1782.             ->getRepository(Token::class)
  1783.             ->findOneBy(['token' => $request->query->get('token')]);
  1784.         if (!$token) {
  1785.             return new Response(json_encode([
  1786.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1787.                 "status" => 404,
  1788.             ]), 404);
  1789.         }
  1790.         // get token age
  1791.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1792.         // if the token if older than 7 days
  1793.         if ($dateDiff->7) {
  1794.             $entityManager->remove($token);
  1795.             $entityManager->flush();
  1796.             return $this->json([
  1797.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1798.                 'path' => 'src/Controller/ClientController.php',
  1799.                 "status" => 401,
  1800.             ], 401);
  1801.         }
  1802.         if ($audio != $token->getIdAudio()) {
  1803.             return new Response(json_encode([
  1804.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  1805.                 "status" => 404,
  1806.             ]), 404);
  1807.         }
  1808.         /** @var Rdv[] */
  1809.         $rdvs $this->getDoctrine()
  1810.             ->getRepository(Rdv::class)
  1811.             ->findBy(['id_audio' => $audio->getId()]);
  1812.         return new Response(json_encode(([
  1813.             "content" => count($rdvs),
  1814.             "status" => 200,
  1815.         ])));
  1816.     }
  1817.     /**
  1818.      * @Route("/audio/{id}/rdvsDate/count", name="getCountAudioRdvsBetweenDate", methods={"GET","HEAD"})
  1819.      */
  1820.     public function getCountAudioRdvsBetweenDate(Request $requestAudio $audio)
  1821.     {
  1822.         if (!$request->query->get('token')) {
  1823.             return new Response(json_encode([
  1824.                 "message" => "Pas de token n'a été spécifié",
  1825.                 "status" => 401,
  1826.             ]), 401);
  1827.         }
  1828.         $entityManager $this->getDoctrine()->getManager();
  1829.         /** @var Token */
  1830.         $token $this->getDoctrine()
  1831.             ->getRepository(Token::class)
  1832.             ->findOneBy(['token' => $request->query->get('token')]);
  1833.         if (!$token) {
  1834.             return new Response(json_encode([
  1835.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1836.                 "status" => 404,
  1837.             ]), 404);
  1838.         }
  1839.         // get token age
  1840.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1841.         // if the token if older than 7 days
  1842.         if ($dateDiff->7) {
  1843.             $entityManager->remove($token);
  1844.             $entityManager->flush();
  1845.             return $this->json([
  1846.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1847.                 'path' => 'src/Controller/ClientController.php',
  1848.                 "status" => 401,
  1849.             ], 401);
  1850.         }
  1851.         if ($audio != $token->getIdAudio()) {
  1852.             return new Response(json_encode([
  1853.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  1854.                 "status" => 404,
  1855.             ]), 404);
  1856.         }
  1857.         /** @var Rdv[] */
  1858.         $allRdvs $this->getDoctrine()
  1859.             ->getRepository(Rdv::class)
  1860.             ->findOnlyRdvAudioBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1861.         /** @var Rdv[] */
  1862.         $rdvs $this->getDoctrine()
  1863.             ->getRepository(Rdv::class)
  1864.             ->findOnlyRdvAudioWithoutTestBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1865.         /** @var Rdv[] */
  1866.         $rdvsWithTest $this->getDoctrine()
  1867.             ->getRepository(Rdv::class)
  1868.             ->findOnlyRdvAudioWithTestBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1869.         /** @var Rdv[] */
  1870.         $allRdvsCanceled $this->getDoctrine()
  1871.             ->getRepository(Rdv::class)
  1872.             ->findCanceledRdvAudioBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1873.         /** @var Rdv[] */
  1874.         $allRdvsCanceledCentre $this->getDoctrine()
  1875.             ->getRepository(Rdv::class)
  1876.             ->findCanceledRdvCentreBetweenDate(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1877.         /** @var Rdv[] */
  1878.         $rdvsClosed $this->getDoctrine()
  1879.             ->getRepository(Rdv::class)
  1880.             ->findClosedRdvBetweenDate(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1881.         $myLead 0;
  1882.         $rdvsCanceled $this->getDoctrine()
  1883.             ->getRepository(Rdv::class)
  1884.             ->findCanceledRdvAudioBetweenDateWithoutTest($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1885.         foreach ($rdvsCanceled as $rdvc) {
  1886.             if (!is_null($rdvc->getIdClient())) {
  1887.                 $rdvClient $this->getDoctrine()
  1888.                     ->getRepository(Rdv::class)
  1889.                     ->findRDVLeadByClient(new DateTime($request->query->get('debut')), $request->query->get('centre'), $rdvc->getIdClient()->getID());
  1890.                 if (count($rdvClient) == 0) {
  1891.                     $myLead $myLead 1;
  1892.                 }
  1893.             }
  1894.         }
  1895.         $myLeadAdvanced 0;
  1896.         $rdvsCanceledA $this->getDoctrine()
  1897.             ->getRepository(Rdv::class)
  1898.             ->findCanceledRdvAudioBetweenDateWithTest($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1899.         foreach ($rdvsCanceledA as $rdvc) {
  1900.             if (!is_null($rdvc->getIdClient())) {
  1901.                 $rdvClient $this->getDoctrine()
  1902.                     ->getRepository(Rdv::class)
  1903.                     ->findRDVLeadByClient(new DateTime($request->query->get('debut')), $request->query->get('centre'), $rdvc->getIdClient()->getID());
  1904.                 if (count($rdvClient) == 0) {
  1905.                     $myLeadAdvanced $myLeadAdvanced 1;
  1906.                 }
  1907.             }
  1908.         }
  1909.         /**** MY RDV Centre****/
  1910.         $myrdvCentre 0;
  1911.         $rdvs $this->getDoctrine()
  1912.             ->getRepository(Rdv::class)
  1913.             ->findRDVCentreBetweenDateWithoutTest(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1914.         $myrdvCentre count($rdvs);
  1915.         /**** MY RDV ADVANCED ****/
  1916.         $myRdvAdvancedCentre 0;
  1917.         $rdvsA $this->getDoctrine()
  1918.             ->getRepository(Rdv::class)
  1919.             ->findRDVCentreBetweenDateWithTestId(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1920.         $myRdvAdvancedCentre count($rdvsA);
  1921.         /**** FIRST RDV BY MOTIF PREMIER RDV ****/
  1922.         $myFirstRdv 0;
  1923.         $rdvsFirst $this->getDoctrine()
  1924.             ->getRepository(Rdv::class)
  1925.             ->findFirstRdv(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1926.         $myFirstRdv count($rdvsFirst);
  1927.         /****  RDV BY RECHERCHE RESULT VIA MYAUDIO ****/
  1928.         $myAudioRdv 0;
  1929.         $audioRdv $this->getDoctrine()
  1930.             ->getRepository(Rdv::class)
  1931.             ->findRdvMyAudio(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1932.         $myAudioRdv count($audioRdv);
  1933.         /****  RDV BY GENDER ****/
  1934.         $myRdvByGender 0;
  1935.         $audioRdvGender $this->getDoctrine()
  1936.             ->getRepository(Rdv::class)
  1937.             ->countMaleAndFemalePatient(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1938.         $myRdvByGender $audioRdvGender;
  1939.         /****  RDV BY AGE ****/
  1940.         $myRdvByAge 0;
  1941.         $audioRdvAge $this->getDoctrine()
  1942.             ->getRepository(Rdv::class)
  1943.             ->countClientsByAgeGroupsPatient(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1944.         $myRdvByAge $audioRdvAge;
  1945.         //  dd($myRdvByAge);
  1946.         /**** MY LEAD ****/
  1947.         $myLeadCentre 0;
  1948.         $rdvsCanceled $this->getDoctrine()
  1949.             ->getRepository(Rdv::class)
  1950.             ->findCanceledRdvCentreBetweenDateWithoutTest(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1951.         foreach ($rdvsCanceled as $rdvc) {
  1952.             if (!is_null($rdvc->getIdClient())) {
  1953.                 $rdvClient $this->getDoctrine()
  1954.                     ->getRepository(Rdv::class)
  1955.                     ->findRDVLeadByClient(new DateTime($request->query->get('debut')), $request->query->get('centre'), $rdvc->getIdClient()->getID());
  1956.                 if (count($rdvClient) == 0) {
  1957.                     $myLeadCentre $myLeadCentre 1;
  1958.                 }
  1959.             }
  1960.         }
  1961.         /**** MY LEAD ADVANCED****/
  1962.         $myLeadAdvancedCentre 0;
  1963.         $rdvsCanceledA $this->getDoctrine()
  1964.             ->getRepository(Rdv::class)
  1965.             ->findCanceledRdvCentreBetweenDateWithTest(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1966.         foreach ($rdvsCanceledA as $rdvc) {
  1967.             if (!is_null($rdvc->getIdClient())) {
  1968.                 $rdvClient $this->getDoctrine()
  1969.                     ->getRepository(Rdv::class)
  1970.                     ->findRDVLeadByClient(new DateTime($request->query->get('debut')), $request->query->get('centre'), $rdvc->getIdClient()->getID());
  1971.                 if (count($rdvClient) == 0) {
  1972.                     $myLeadAdvancedCentre $myLeadAdvancedCentre 1;
  1973.                 }
  1974.             }
  1975.         }
  1976.         return $this->json([
  1977.             "rdvs" => count($rdvs),
  1978.             "rdvsFromTest" => count($rdvsWithTest),
  1979.             "allRdvs" => count($allRdvs),
  1980.             "rdvsCanceled" => count($allRdvsCanceled),
  1981.             "rdvsClosed" => $rdvsClosed,
  1982.             "myRdvByGender" => $myRdvByGender,
  1983.             "myLead" => $myLead,
  1984.             "myRdvByAge" => $myRdvByAge,
  1985.             "myAudioRdv" => $myAudioRdv,
  1986.             "myLeadAdvanced" => $myLeadAdvanced,
  1987.             "myRDVCentre" => $myrdvCentre,
  1988.             "myRDVAdancedCentre" => $myRdvAdvancedCentre,
  1989.             "myLeadCentre" => $myLeadCentre,
  1990.             "myLeadAdvancedCentre" => $myLeadAdvancedCentre,
  1991.             "rdvsCanceledCentre" => count($allRdvsCanceledCentre),
  1992.             "myFirstRdv" => $myFirstRdv,
  1993.             "status" => 200,
  1994.         ]);
  1995.     }
  1996.     /**
  1997.      * @Route("/rdvs/old/clientTemp/{id}", name="getOldRdvsByClientTempId", methods={"GET","HEAD"})
  1998.      */
  1999.     public function getOldRdvsByClientTempId(Request $requestClientTemp $clientTempPublicFunction $publicFunction)
  2000.     {
  2001.         if (!$request->query->get('token')) {
  2002.             return new Response(json_encode([
  2003.                 "message" => "Pas de token n'a été spécifié",
  2004.                 "status" => 401,
  2005.             ]), 401);
  2006.         }
  2007.         $entityManager $this->getDoctrine()->getManager();
  2008.         /** @var Token */
  2009.         $token $this->getDoctrine()
  2010.             ->getRepository(Token::class)
  2011.             ->findOneBy(['token' => $request->query->get('token')]);
  2012.         if (!$token) {
  2013.             return new Response(json_encode([
  2014.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2015.                 "status" => 404,
  2016.             ]), 404);
  2017.         }
  2018.         // get token age
  2019.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2020.         // if the token if older than 7 days
  2021.         if ($dateDiff->7) {
  2022.             $entityManager->remove($token);
  2023.             $entityManager->flush();
  2024.             return $this->json([
  2025.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2026.                 'path' => 'src/Controller/ClientController.php',
  2027.                 "status" => 401,
  2028.             ], 401);
  2029.         }
  2030.         if ($clientTemp->getIdAudio() != $token->getIdAudio()) {
  2031.             return new Response(json_encode([
  2032.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  2033.                 "status" => 404,
  2034.             ]), 404);
  2035.         }
  2036.         if ($request->query->get('audio')) {
  2037.             /** @var ActivityRepository */
  2038.             $activityRepo $this->getDoctrine()->getRepository(Rdv::class);
  2039.             if ($request->query->get('limit')) {
  2040.                 /** @var Rdv[] */
  2041.                 $rdvs $activityRepo
  2042.                     ->findLastsOldRdvsWithLimitTemp($request->query->get('limit'), $clientTemp->getId(), $request->query->get('audio'), new DateTime());
  2043.                 $rdvResult = new ArrayCollection();
  2044.             } else {
  2045.                 /** @var Rdv[] */
  2046.                 $rdvs $activityRepo
  2047.                     ->findOldRdvsTemp($clientTemp->getId(), $request->query->get('audio'), new DateTime());
  2048.                 $rdvResult = new ArrayCollection();
  2049.             }
  2050.             foreach ($rdvs as $rdv) {
  2051.                 if ($rdv->getIdEtat()->getId() != 1) {
  2052.                     continue;
  2053.                 }
  2054.                 /** @var AudioMotif */
  2055.                 $audioMotif $this->getDoctrine()
  2056.                     ->getRepository(AudioMotif::class)
  2057.                     ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  2058.                 if (!$audioMotif) {
  2059.                     continue;
  2060.                 }
  2061.                 $duration '';
  2062.                 if (is_null($rdv->getDuration())) {
  2063.                     $duration $audioMotif->getDuration();
  2064.                 } else {
  2065.                     $duration $rdv->getDuration();
  2066.                 }
  2067.                 $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  2068.                 /** @var Rdv[] */
  2069.                 $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  2070.                     ->findAllReviewsCentre($rdvCentre->getId());
  2071.                 $rdvItem = [
  2072.                     "id" => $rdv->getId(),
  2073.                     "motif_id" => $rdv->getIdMotif()->getId(),
  2074.                     "duration" => $duration,
  2075.                     "color" => $audioMotif->getColor(),
  2076.                     "audio_id" => $rdv->getIdAudio()->getId(),
  2077.                     "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  2078.                     "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  2079.                     "client_id_temp" => $rdv->getIdClientTemp()->getId(),
  2080.                     "client_name" => $rdv->getIdClientTemp()->getName() . " " $rdv->getIdClientTemp()->getLastname(),
  2081.                     "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  2082.                     "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  2083.                     "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  2084.                     "testclient" => $rdv->getTestClient() ? [
  2085.                         "result" => $rdv->getTestClient()->getResultTonal(),
  2086.                         "date" => $rdv->getTestClient()->getDate(),
  2087.                         "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  2088.                     ] : null,
  2089.                     "name" => $rdvCentre->getName(),
  2090.                     "phone" => $rdvCentre->getPhone(),
  2091.                     "imgUrl" => $rdvCentre->getImgUrl(),
  2092.                     "address" => $rdvCentre->getAddress(),
  2093.                     "postale" => $rdvCentre->getPostale(),
  2094.                     "city" => $rdvCentre->getCity(),
  2095.                     "etat_id" => $rdvCentre->getId(),
  2096.                     "averageRating" => $publicFunction->calculateRating($centreRdvs),
  2097.                     "nbrReview" => count($centreRdvs),
  2098.                     "acceptedCurrency" => "CB Chèque",
  2099.                     "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  2100.                     "note" => $rdv->getNote(),
  2101.                     "comment" => $rdv->getComment(),
  2102.                     "review" => $rdv->getReview(),
  2103.                 ];
  2104.                 $rdvResult->add($rdvItem);
  2105.             }
  2106.         }
  2107.         if (count($rdvResult) > 0) {
  2108.             return new Response(json_encode(([
  2109.                 "rdv" => $rdvResult->toArray(),
  2110.                 "status" => 200,
  2111.             ])));
  2112.         } else {
  2113.             return new Response(json_encode(([
  2114.                 "message" => "Aucun rendez-vous n'a été trouvé!",
  2115.                 'path' => 'src/Controller/RdvController.php',
  2116.                 "status" => 404,
  2117.             ])));
  2118.         }
  2119.     }
  2120.     /**
  2121.      * @Route("/rdvs/old/clientTemp/{id}/centre", name="getOldRdvsByClientTempIdByCentre", methods={"GET","HEAD"})
  2122.      */
  2123.     public function getOldRdvsByClientTempIdByCentre(Request $requestClientTemp $clientTempPublicFunction $publicFunction)
  2124.     {
  2125.         if (!$request->query->get('token')) {
  2126.             return new Response(json_encode([
  2127.                 "message" => "Pas de token n'a été spécifié",
  2128.                 "status" => 401,
  2129.             ]), 401);
  2130.         }
  2131.         $entityManager $this->getDoctrine()->getManager();
  2132.         /** @var Token */
  2133.         $token $this->getDoctrine()
  2134.             ->getRepository(Token::class)
  2135.             ->findOneBy(['token' => $request->query->get('token')]);
  2136.         if (!$token) {
  2137.             return new Response(json_encode([
  2138.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2139.                 "status" => 404,
  2140.             ]), 404);
  2141.         }
  2142.         // get token age
  2143.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2144.         // if the token if older than 7 days
  2145.         if ($dateDiff->7) {
  2146.             $entityManager->remove($token);
  2147.             $entityManager->flush();
  2148.             return $this->json([
  2149.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2150.                 'path' => 'src/Controller/ClientController.php',
  2151.                 "status" => 401,
  2152.             ], 401);
  2153.         }
  2154.         $audioCentre $this->getDoctrine()
  2155.             ->getRepository(AudioCentre::class)
  2156.             ->findOneBy(['id_audio' => $token->getIdAudio()]);
  2157.         // we add the multi-centre so we wil desable the autorisation 
  2158.         /*
  2159.         if ($clientTemp->getIdCentre() != $audioCentre->getIdCentre()) {
  2160.             return new Response(json_encode([
  2161.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  2162.                 "status" => 404,
  2163.             ]), 404);
  2164.         }
  2165. */
  2166.         /** @var ActivityRepository */
  2167.         $activityRepo $this->getDoctrine()->getRepository(Rdv::class);
  2168.         if ($request->query->get('limit')) {
  2169.             /** @var Rdv[] */
  2170.             $rdvs $activityRepo
  2171.                 ->findLastsOldRdvsWithLimitTempByCentre($request->query->get('limit'), $clientTemp->getId(), $audioCentre->getIdCentre()->getId(), new DateTime());
  2172.             $rdvResult = new ArrayCollection();
  2173.         } else {
  2174.             /** @var Rdv[] */
  2175.             $rdvs $activityRepo
  2176.                 ->findOldRdvsTempByCentre($clientTemp->getId(), $audioCentre->getIdCentre()->getId(), new DateTime());
  2177.             $rdvResult = new ArrayCollection();
  2178.         }
  2179.         foreach ($rdvs as $rdv) {
  2180.             /*if ($rdv->getIdEtat()->getId() != 1) {
  2181.                 continue;
  2182.             }*/
  2183.             /** @var AudioMotif */
  2184.             $audioMotif $this->getDoctrine()
  2185.                 ->getRepository(AudioMotif::class)
  2186.                 ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  2187.             if (!$audioMotif) {
  2188.                 continue;
  2189.             }
  2190.             $duration '';
  2191.             if (is_null($rdv->getDuration())) {
  2192.                 $duration $audioMotif->getDuration();
  2193.             } else {
  2194.                 $duration $rdv->getDuration();
  2195.             }
  2196.             $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  2197.             /** @var Rdv[] */
  2198.             $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  2199.                 ->findAllReviewsCentre($rdvCentre->getId());
  2200.             $rdvItem = [
  2201.                 "id" => $rdv->getId(),
  2202.                 "motif_id" => $rdv->getIdMotif()->getId(),
  2203.                 "duration" => $duration,
  2204.                 "color" => $audioMotif->getColor(),
  2205.                 "audio_id" => $rdv->getIdAudio()->getId(),
  2206.                 "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  2207.                 "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  2208.                 "client_id_temp" => $rdv->getIdClientTemp()->getId(),
  2209.                 "client_name" => $rdv->getIdClientTemp()->getName() . " " $rdv->getIdClientTemp()->getLastname(),
  2210.                 "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  2211.                 "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  2212.                 "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  2213.                 "testclient" => $rdv->getTestClient() ? [
  2214.                     "result" => $rdv->getTestClient()->getResultTonal(),
  2215.                     "date" => $rdv->getTestClient()->getDate(),
  2216.                     "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  2217.                 ] : null,
  2218.                 "name" => $rdvCentre->getName(),
  2219.                 "phone" => $rdvCentre->getPhone(),
  2220.                 "imgUrl" => $rdvCentre->getImgUrl(),
  2221.                 "address" => $rdvCentre->getAddress(),
  2222.                 "postale" => $rdvCentre->getPostale(),
  2223.                 "city" => $rdvCentre->getCity(),
  2224.                 "etat_id" => $rdvCentre->getId(),
  2225.                 "averageRating" => $publicFunction->calculateRating($centreRdvs),
  2226.                 "nbrReview" => count($centreRdvs),
  2227.                 "acceptedCurrency" => "CB Chèque",
  2228.                 "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  2229.                 "note" => $rdv->getNote(),
  2230.                 "comment" => $rdv->getComment(),
  2231.                 "review" => $rdv->getReview(),
  2232.                 "status" => $rdv->getIdEtat()->getLibelle()
  2233.             ];
  2234.             $rdvResult->add($rdvItem);
  2235.         }
  2236.         if (count($rdvResult) > 0) {
  2237.             return new Response(json_encode(([
  2238.                 "rdv" => $rdvResult->toArray(),
  2239.                 "status" => 200,
  2240.             ])));
  2241.         } else {
  2242.             return new Response(json_encode(([
  2243.                 "message" => "Aucun rendez-vous n'a été trouvé!",
  2244.                 'path' => 'src/Controller/RdvController.php',
  2245.                 "status" => 404,
  2246.             ])));
  2247.         }
  2248.     }
  2249.     /**
  2250.      * @Route("/rdvs/clientTemp/{id}", name="getRdvsByClientTempID", methods={"GET","HEAD"})
  2251.      */
  2252.     public function getRdvsByClientTempID(Request $requestClientTemp $clientTempPublicFunction $publicFunction)
  2253.     {
  2254.         if (!$request->query->get('token')) {
  2255.             return new Response(json_encode([
  2256.                 "message" => "Pas de token n'a été spécifié",
  2257.                 "status" => 401,
  2258.             ]), 401);
  2259.         }
  2260.         $entityManager $this->getDoctrine()->getManager();
  2261.         /** @var Token */
  2262.         $token $this->getDoctrine()
  2263.             ->getRepository(Token::class)
  2264.             ->findOneBy(['token' => $request->query->get('token')]);
  2265.         if (!$token) {
  2266.             return new Response(json_encode([
  2267.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2268.                 "status" => 404,
  2269.             ]), 404);
  2270.         }
  2271.         // get token age
  2272.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2273.         // if the token if older than 7 days
  2274.         if ($dateDiff->7) {
  2275.             $entityManager->remove($token);
  2276.             $entityManager->flush();
  2277.             return $this->json([
  2278.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2279.                 'path' => 'src/Controller/ClientController.php',
  2280.                 "status" => 401,
  2281.             ], 401);
  2282.         }
  2283.         if ($clientTemp->getIdAudio() != $token->getIdAudio()) {
  2284.             return new Response(json_encode([
  2285.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  2286.                 "status" => 404,
  2287.             ]), 404);
  2288.         }
  2289.         /** @var Rdv[] */
  2290.         $rdvs $this->getDoctrine()
  2291.             ->getRepository(Rdv::class)
  2292.             ->findBy(['id_client_temp' => $clientTemp->getId(), 'id_audio' => $token->getIdAudio()]);
  2293.         $rdvResult = new ArrayCollection();
  2294.         if ($request->query->get('old')) {
  2295.             $oldRdvResult = new ArrayCollection();
  2296.         }
  2297.         foreach ($rdvs as $rdv) {
  2298.             if ($rdv->getIdEtat()->getId() != null) {
  2299.                 if ($rdv->getIdEtat()->getId() == 1) {
  2300.                     /** @var AudioMotif */
  2301.                     $audioMotif $this->getDoctrine()
  2302.                         ->getRepository(AudioMotif::class)
  2303.                         ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $token->getIdAudio()]);
  2304.                     /** @var Rdv[] */
  2305.                     $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  2306.                         ->findAllReviewsCentre($rdv->getIdCentre()->getId());
  2307.                     $duration '';
  2308.                     if (is_null($rdv->getDuration())) {
  2309.                         $duration $audioMotif->getDuration();
  2310.                     } else {
  2311.                         $duration $rdv->getDuration();
  2312.                     }
  2313.                     $rdvItem = [
  2314.                         "id" => $rdv->getId(),
  2315.                         "motif_id" => $rdv->getIdMotif()->getId(),
  2316.                         "duration" => $duration,
  2317.                         "color" => $audioMotif->getColor(),
  2318.                         "audio_id" => $rdv->getIdAudio()->getId(),
  2319.                         "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  2320.                         "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  2321.                         "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  2322.                         "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  2323.                         "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  2324.                         "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  2325.                         "client_name" => $rdv->getIdClientTemp()->getName() . " " $rdv->getIdClientTemp()->getLastname(),
  2326.                         "averageRating" => $publicFunction->calculateRating($centreRdvs),
  2327.                         "nbrReview" => count($centreRdvs),
  2328.                         "acceptedCurrency" => "CB Chèque",
  2329.                         "name" => $rdv->getIdCentre()->getName(),
  2330.                         "imgUrl" => $rdv->getIdCentre()->getImgUrl(),
  2331.                         "address" => $rdv->getIdCentre()->getAddress(),
  2332.                         "phone" => $rdv->getIdCentre()->getPhone(),
  2333.                         "etat_id" => $rdv->getIdEtat()->getId(),
  2334.                         "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  2335.                         "comment" => $rdv->getComment(),
  2336.                         "note" => $rdv->getNote(),
  2337.                         "review" => $rdv->getReview(),
  2338.                     ];
  2339.                     if ($rdv->getDate() >= new DateTime()) {
  2340.                         $rdvResult->add($rdvItem);
  2341.                     } else if ($request->query->get('old')) {
  2342.                         $oldRdvResult->add($rdvItem);
  2343.                     }
  2344.                 }
  2345.             }
  2346.         }
  2347.         if ($request->query->get('old')) {
  2348.             if (count($rdvResult) > || count($oldRdvResult) > 0) {
  2349.                 return new Response(json_encode(([
  2350.                     "rdv" => $rdvResult->toArray(),
  2351.                     "oldRdv" => $oldRdvResult->toArray(),
  2352.                     "status" => 200,
  2353.                 ])));
  2354.             } else {
  2355.                 return new Response(json_encode(([
  2356.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  2357.                     'path' => 'src/Controller/RdvController.php',
  2358.                     "status" => 404,
  2359.                 ])));
  2360.             }
  2361.         } else {
  2362.             if (count($rdvResult) > 0) {
  2363.                 return new Response(json_encode(([
  2364.                     "content" => $rdvResult->toArray(),
  2365.                     "status" => 200,
  2366.                 ])));
  2367.             } else {
  2368.                 return new Response(json_encode(([
  2369.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  2370.                     'path' => 'src/Controller/RdvController.php',
  2371.                     "status" => 404,
  2372.                 ])));
  2373.             }
  2374.         }
  2375.     }
  2376.     /**
  2377.      * @Route("/rdvs/clientTemp/{id}/centre", name="getRdvsByClientTempIDByCentre", methods={"GET","HEAD"})
  2378.      */
  2379.     public function getRdvsByClientTempIDByCentre(Request $requestClientTemp $clientTempPublicFunction $publicFunction)
  2380.     {
  2381.         if (!$request->query->get('token')) {
  2382.             return new Response(json_encode([
  2383.                 "message" => "Pas de token n'a été spécifié",
  2384.                 "status" => 401,
  2385.             ]), 401);
  2386.         }
  2387.         $entityManager $this->getDoctrine()->getManager();
  2388.         /** @var Token */
  2389.         $token $this->getDoctrine()
  2390.             ->getRepository(Token::class)
  2391.             ->findOneBy(['token' => $request->query->get('token')]);
  2392.         if (!$token) {
  2393.             return new Response(json_encode([
  2394.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2395.                 "status" => 404,
  2396.             ]), 404);
  2397.         }
  2398.         // get token age
  2399.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2400.         // if the token if older than 7 days
  2401.         if ($dateDiff->7) {
  2402.             $entityManager->remove($token);
  2403.             $entityManager->flush();
  2404.             return $this->json([
  2405.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2406.                 'path' => 'src/Controller/ClientController.php',
  2407.                 "status" => 401,
  2408.             ], 401);
  2409.         }
  2410.         $audioCentre $this->getDoctrine()
  2411.             ->getRepository(AudioCentre::class)
  2412.             ->findOneBy(['id_audio' => $token->getIdAudio()]);
  2413.         // we add the multi-centre so we wil desable the autorisation 
  2414.         /*    
  2415.         if ($clientTemp->getIdCentre() != $audioCentre->getIdCentre()) {
  2416.             return new Response(json_encode([
  2417.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  2418.                 "status" => 404,
  2419.             ]), 404);
  2420.         }*/
  2421.         /** @var Rdv[] */
  2422.         $rdvs $this->getDoctrine()
  2423.             ->getRepository(Rdv::class)
  2424.             ->findBy(['id_client_temp' => $clientTemp->getId(), 'id_centre' => $audioCentre->getIdCentre()]);
  2425.         $rdvResult = new ArrayCollection();
  2426.         if ($request->query->get('old')) {
  2427.             $oldRdvResult = new ArrayCollection();
  2428.         }
  2429.         foreach ($rdvs as $rdv) {
  2430.             if ($rdv->getIdEtat()->getId() != null) {
  2431.                 if ($rdv->getIdEtat()->getId() != 6) {
  2432.                     // if ($rdv->getIdEtat()->getId() == 1) {
  2433.                     /** @var AudioMotif */
  2434.                     $audioMotif $this->getDoctrine()
  2435.                         ->getRepository(AudioMotif::class)
  2436.                         ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  2437.                     /** @var Rdv[] */
  2438.                     $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  2439.                         ->findAllReviewsCentre($rdv->getIdCentre()->getId());
  2440.                     $duration '';
  2441.                     if (is_null($rdv->getDuration())) {
  2442.                         $duration $audioMotif->getDuration();
  2443.                     } else {
  2444.                         $duration $rdv->getDuration();
  2445.                     }
  2446.                     $rdvItem = [
  2447.                         "id" => $rdv->getId(),
  2448.                         "motif_id" => $rdv->getIdMotif()->getId(),
  2449.                         "duration" => $duration,
  2450.                         "color" => $audioMotif->getColor(),
  2451.                         "audio_id" => $rdv->getIdAudio()->getId(),
  2452.                         "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  2453.                         "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  2454.                         "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  2455.                         "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  2456.                         "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  2457.                         "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  2458.                         "client_name" => $rdv->getIdClientTemp()->getName() . " " $rdv->getIdClientTemp()->getLastname(),
  2459.                         "averageRating" => $publicFunction->calculateRating($centreRdvs),
  2460.                         "nbrReview" => count($centreRdvs),
  2461.                         "acceptedCurrency" => "CB Chèque",
  2462.                         "name" => $rdv->getIdCentre()->getName(),
  2463.                         "imgUrl" => $rdv->getIdCentre()->getImgUrl(),
  2464.                         "address" => $rdv->getIdCentre()->getAddress(),
  2465.                         "phone" => $rdv->getIdCentre()->getPhone(),
  2466.                         "etat_id" => $rdv->getIdEtat()->getId(),
  2467.                         "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  2468.                         "comment" => $rdv->getComment(),
  2469.                         "note" => $rdv->getNote(),
  2470.                         "review" => $rdv->getReview(),
  2471.                         "status" => $rdv->getIdEtat()->getLibelle()
  2472.                     ];
  2473.                     if ($rdv->getDate() >= new DateTime()) {
  2474.                         $rdvResult->add($rdvItem);
  2475.                     } else if ($request->query->get('old')) {
  2476.                         $oldRdvResult->add($rdvItem);
  2477.                     }
  2478.                 }
  2479.             }
  2480.         }
  2481.         if ($request->query->get('old')) {
  2482.             if (count($rdvResult) > || count($oldRdvResult) > 0) {
  2483.                 return new Response(json_encode(([
  2484.                     "rdv" => $rdvResult->toArray(),
  2485.                     "oldRdv" => $oldRdvResult->toArray(),
  2486.                     "status" => 200,
  2487.                 ])));
  2488.             } else {
  2489.                 return new Response(json_encode(([
  2490.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  2491.                     'path' => 'src/Controller/RdvController.php',
  2492.                     "status" => 404,
  2493.                 ])));
  2494.             }
  2495.         } else {
  2496.             if (count($rdvResult) > 0) {
  2497.                 return new Response(json_encode(([
  2498.                     "content" => $rdvResult->toArray(),
  2499.                     "status" => 200,
  2500.                 ])));
  2501.             } else {
  2502.                 return new Response(json_encode(([
  2503.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  2504.                     'path' => 'src/Controller/RdvController.php',
  2505.                     "status" => 404,
  2506.                 ])));
  2507.             }
  2508.         }
  2509.     }
  2510.     /**
  2511.      * @Route("/rdv", name="postRdv", methods={"POST"})
  2512.      */
  2513.     public function postRdv(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendarRdvSmsService $rdvSmsAppointmentCallService $Callservice): Response
  2514.     {
  2515.         $data json_decode($request->getContent(), true);
  2516.         if (!isset($data["token"])) {
  2517.             return new Response(json_encode([
  2518.                 "message" => "Pas de token n'a été spécifié",
  2519.                 "status" => 401,
  2520.             ]), 401);
  2521.         }
  2522.         $entityManager $this->getDoctrine()->getManager();
  2523.         /** @var Token */
  2524.         $token $this->getDoctrine()
  2525.             ->getRepository(Token::class)
  2526.             ->findOneBy(['token' => $data["token"]]);
  2527.         if (!$token) {
  2528.             return new Response(json_encode([
  2529.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2530.                 "status" => 404,
  2531.             ]), 404);
  2532.         }
  2533.         // get token age
  2534.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2535.         // if the token if older than 7 days
  2536.         if ($dateDiff->7) {
  2537.             $entityManager->remove($token);
  2538.             $entityManager->flush();
  2539.             return $this->json([
  2540.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2541.                 'path' => 'src/Controller/ClientController.php',
  2542.                 "status" => 401,
  2543.             ], 401);
  2544.         }
  2545.         // makes the rdv
  2546.         $rdv = new Rdv();
  2547.         if ($token->getIdAudio()) {
  2548.             //if the token if for an audio
  2549.             $audio $token->getIdAudio();
  2550.             if ((isset($data["client_id"]))) {
  2551.                 $client $this->getDoctrine()
  2552.                     ->getRepository(Client::class)
  2553.                     ->findOneBy(['id' => $data["client_id"]]);
  2554.             } else {
  2555.                 $client $this->getDoctrine()
  2556.                     ->getRepository(ClientTemp::class)
  2557.                     ->findOneBy(['id' => $data["client_id_temp"]]);
  2558.             }
  2559.             if ($client == null) {
  2560.                 return new Response(json_encode(([
  2561.                     'message' => 'Error, no client found at this id',
  2562.                     'path' => 'src/Controller/RdvController.php',
  2563.                     "status" => 400,
  2564.                 ])), 400);
  2565.             }
  2566.         } elseif ($token->getIdClient()) {
  2567.             //if the token if for a client
  2568.             $client $token->getIdClient();
  2569.             /** @var ActivityRepository */
  2570.             $activityRepo $this->getDoctrine();
  2571.             /** @var TestClient */
  2572.             $testClient $activityRepo
  2573.                 ->getRepository(TestClient::class)
  2574.                 ->getLatestTestClient($client);
  2575.             // add the test to the rdv if the client had one
  2576.             if ($testClient)
  2577.             // add the test to the rdv if the test isn't already on another rdv
  2578.             {
  2579.                 if (!$testClient->getRdv()) {
  2580.                     $rdv->setTestClient($testClient);
  2581.                 }
  2582.             }
  2583.             /** @var Audio */
  2584.             $audio $this->getDoctrine()
  2585.                 ->getRepository(Audio::class)
  2586.                 ->findOneBy(['id' => $data["audio_id"]]);
  2587.             if (isset($data["proche_id"])) {
  2588.                 $proche $this->getDoctrine()
  2589.                     ->getRepository(Proches::class)
  2590.                     ->findOneBy(['id' => $data["proche_id"], "id_client" => $client]);
  2591.             }
  2592.             if (!$audio) {
  2593.                 return new Response(json_encode(([
  2594.                     'message' => "Erreur, pas d'audio n'a été trouvé à cette id.",
  2595.                     'path' => 'src/Controller/RdvController.php',
  2596.                 ])), 400);
  2597.             }
  2598.             /** @var ClientBlocked */
  2599.             $clientBlocked $this->getDoctrine()
  2600.                 ->getRepository(ClientBlocked::class)
  2601.                 ->findOneBy(["id_audio" => $audio"id_client" => $client]);
  2602.             if ($clientBlocked) {
  2603.                 return new Response(json_encode(([
  2604.                     'message' => 'Erreur, vous avez été bloqué par cette audioprothésiste.',
  2605.                     'path' => 'src/Controller/RdvController.php',
  2606.                 ])), 400);
  2607.             }
  2608.             // set the rdv test
  2609.         } else {
  2610.             return new Response(json_encode(([
  2611.                 'message' => "Erreur, ce token n'est pas celui d'un client ou audioprothèsiste.",
  2612.                 'path' => 'src/Controller/RdvController.php',
  2613.             ])), 400);
  2614.         }
  2615.         $rdv->setIdAudio($audio);
  2616.         if (isset($proche)) {
  2617.             $rdv->setIdProche($proche);
  2618.         }
  2619.         if (isset($data["client_id_temp"])) {
  2620.             $rdv->setIdClientTemp($client);
  2621.         } else {
  2622.             $rdv->setIdClient($client);
  2623.         }
  2624.         if (isset($data["isMyaudio"])) {
  2625.             $rdv->setIsMyaudio(true);
  2626.         }
  2627.         if (isset($data["isRdvLead"])) {
  2628.             $rdv->setIsRdvLp(true);
  2629.         }
  2630.         if (isset($data["isRdvRapide"])) {
  2631.             $rdv->setIsRdvRapide(true);
  2632.         }
  2633.         if (isset($data["duree"])) {
  2634.             $rdv->setDuration($data["duree"]);
  2635.         }
  2636.         if (isset($data["color"])) {
  2637.             $rdv->setColor($data["color"]);
  2638.         }
  2639.         if (isset($data["lead"])) {
  2640.             $lead $this->getDoctrine()
  2641.                 ->getRepository(LeadRdv::class)
  2642.                 ->find($data["lead"]);
  2643.             $lead->setRdv($rdv);
  2644.             $leadStatus $this->entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'rdv_valider']);
  2645.             if ($leadStatus) {
  2646.                 $lead->setLeadStatus($leadStatus);
  2647.             }
  2648.         }
  2649.         /** @var Centre */
  2650.         if (isset($data["centre_id"])) {
  2651.             $centre $this->getDoctrine()
  2652.                 ->getRepository(Centre::class)
  2653.                 ->findOneBy(['id' => $data["centre_id"]]);
  2654.             if ($centre == null) {
  2655.                 return new Response(json_encode(([
  2656.                     'message' => 'Error, no centre found at this id',
  2657.                     'path' => 'src/Controller/RdvController.php',
  2658.                     "status" => 400,
  2659.                 ])), 400);
  2660.             }
  2661.             /** @var AudioCentre */
  2662.             $liaison $this->getDoctrine()
  2663.                 ->getRepository(AudioCentre::class)
  2664.                 ->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
  2665.             if ($liaison == null) {
  2666.                 return new Response(json_encode(([
  2667.                     'message' => 'Error, audio isnt part of the centre',
  2668.                     'path' => 'src/Controller/RdvController.php',
  2669.                     "status" => 400,
  2670.                 ])), 400);
  2671.             }
  2672.             $rdv->setIdCentre($centre);
  2673.         } elseif (isset($data["lieu_id"]) && $audio->getIsIndie()) {
  2674.             // tries to set the lieu if it's an audio indie
  2675.             $lieu $this->getDoctrine()
  2676.                 ->getRepository(Lieu::class)
  2677.                 ->findOneBy(['id' => $data["lieu_id"], 'id_gerant' => $data["audio_id"]]);
  2678.             if ($lieu == null) {
  2679.                 return new Response(json_encode(([
  2680.                     'message' => 'Error, no lieu found at this id',
  2681.                     'path' => 'src/Controller/RdvController.php',
  2682.                     "status" => 400,
  2683.                 ])), 400);
  2684.             }
  2685.             $rdv->setIdLieu($lieu);
  2686.         } else {
  2687.             return new Response(json_encode(([
  2688.                 'message' => 'Error, no lieu/centre id',
  2689.                 'path' => 'src/Controller/RdvController.php',
  2690.                 "status" => 400,
  2691.             ])), 400);
  2692.         }
  2693.         /** @var Motif */
  2694.         $motif $this->getDoctrine()
  2695.             ->getRepository(Motif::class)
  2696.             ->find($data["motif_id"]);
  2697.         if ($motif == null) {
  2698.             return new Response(json_encode(([
  2699.                 'message' => 'Error, no motif found at this id',
  2700.                 'path' => 'src/Controller/RdvController.php',
  2701.                 "status" => 400,
  2702.             ])), 400);
  2703.         }
  2704.         /** @var AudioMotif */
  2705.         $audioMotif $this->getDoctrine()
  2706.             ->getRepository(AudioMotif::class)
  2707.             ->findOneBy(["id_audio" => $audio->getId(), "id_motif" => $data["motif_id"]]);
  2708.         if ($audioMotif == null) {
  2709.             return new Response(json_encode(([
  2710.                 'message' => 'Error, no motif of this id found at this audio',
  2711.                 'path' => 'src/Controller/RdvController.php',
  2712.                 "status" => 400,
  2713.             ])), 400);
  2714.         }
  2715.         // remove the taken schedule by rdv to make sure there is no overlap
  2716.         $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  2717.         if (isset($data["note"])) {
  2718.             $rdv->setNote($data["note"]);
  2719.         }
  2720.         // test if the audio is available
  2721.         if ($audio->getIsIndie()) {
  2722.             if (isset($data["centre_id"])) {
  2723.                 if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  2724.                     return new Response(json_encode(([
  2725.                         'message' => 'Error, no horaire found for this audio',
  2726.                         'path' => 'src/Controller/RdvController.php',
  2727.                         "status" => 400,
  2728.                     ])), 400);
  2729.                 }
  2730.                 if ($publicFunction->calculScheduleFitDate($audio\DateTime::createFromFormat("d/m/Y H:i"$data["date"]), $audioMotif->getDuration(), $centre) == false) {
  2731.                     return new Response(json_encode(([
  2732.                         'message' => 'Error, no timestamp found at this time. Line n°' __LINE__,
  2733.                         'path' => 'src/Controller/RdvController.php',
  2734.                         "status" => 400,
  2735.                     ])), 400);
  2736.                 }
  2737.                 $remplacant_id $publicFunction->checkIfRemplacant($liaison->getHoraire(), $date);
  2738.             } else {
  2739.                 if ($lieu->getHoraire() == null || $lieu->getHoraire() == []) {
  2740.                     return new Response(json_encode(([
  2741.                         'message' => 'Error, no horaire found for this audio',
  2742.                         'path' => 'src/Controller/RdvController.php',
  2743.                         "status" => 400,
  2744.                     ])), 400);
  2745.                 }
  2746.                 if ($publicFunction->calculScheduleFitDate($audio\DateTime::createFromFormat("d/m/Y H:i"$data["date"]), $audioMotif->getDuration(), null$lieu) == false) {
  2747.                     return new Response(json_encode(([
  2748.                         'message' => 'Error, no timestamp found at this time. Line n°' __LINE__,
  2749.                         'path' => 'src/Controller/RdvController.php',
  2750.                         "status" => 400,
  2751.                     ])), 400);
  2752.                 }
  2753.                 $remplacant_id $publicFunction->checkIfRemplacant($lieu->getHoraire(), $date);
  2754.             }
  2755.         } else {
  2756.             if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  2757.                 return new Response(json_encode(([
  2758.                     'message' => 'Error, no horaire found for this audio',
  2759.                     'path' => 'src/Controller/RdvController.php',
  2760.                     "status" => 400,
  2761.                 ])), 400);
  2762.             }
  2763.             /*  if (!$publicFunction->calculScheduleFitDate($audio, \DateTime::createFromFormat("d/m/Y H:i", $data["date"]), $audioMotif->getDuration(), $centre))
  2764.                 return new Response(json_encode(([
  2765.                     'message' => "Error, no timestamp found at this time. Motif size: {$audioMotif->getDuration()} Line n°" . __LINE__,
  2766.                     'path' => 'src/Controller/RdvController.php',
  2767.                     "status" => 400,
  2768.                 ])), 400);*/
  2769.             $remplacant_id $publicFunction->checkIfRemplacant($liaison->getHoraire(), \DateTime::createFromFormat("d/m/Y H:i"$data["date"]));
  2770.         }
  2771.         $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  2772.         $existingRdv $this->getDoctrine()
  2773.             ->getRepository(Rdv::class)
  2774.             ->findOneBy([
  2775.                 'date' => $date,
  2776.                 'id_audio' => $audio,
  2777.                 'id_centre' => $rdv->getIdCentre() ?? null,
  2778.                 'id_lieu' => $rdv->getIdLieu()   ?? null,
  2779.             ]);
  2780.         if ($existingRdv) {
  2781.             return new Response(json_encode([
  2782.                 'message' => 'Un rendez-vous est déjà pris pour cette date et ce créneau.',
  2783.                 'status' => 400,
  2784.             ]), 400);
  2785.         }
  2786.         $rdv->setDate($date);
  2787.         $rdv->setDateCreation(\DateTime::createFromFormat("d/m/Y H:i"date('d/m/Y H:i')));
  2788.         /** @var EtatRdv */
  2789.         $etat $this->getDoctrine()
  2790.             ->getRepository(EtatRdv::class)
  2791.             ->findOneBy(['id' => $data["etat_id"]]);
  2792.         if ($etat == null) {
  2793.             return new Response(json_encode(([
  2794.                 'message' => 'Error, no etat found at this id',
  2795.                 'path' => 'src/Controller/RdvController.php',
  2796.                 "status" => 400,
  2797.             ])), 400);
  2798.         }
  2799.         $rdv->setIdEtat($etat);
  2800.         $rdv->setIdMotif($motif);
  2801.         $rdv->setIsAbsence(0);
  2802.         $rdv->setCacher(0);
  2803.         if ($remplacant_id != -1) {
  2804.             $remplacant $this->getDoctrine()
  2805.                 ->getRepository(Remplacant::class)
  2806.                 ->find($remplacant_id);
  2807.             $rdv->setRemplacant($remplacant);
  2808.         }
  2809.         $entityManager $this->getDoctrine()->getManager();
  2810.         $entityManager->persist($rdv);
  2811.         $entityManager->flush();
  2812.         /// SMSEMAIL A décommenter pour autoriser l'envoi de sms / email à la création de rdv par l'audio / le client SMSEMAIL ///
  2813.         $date $rdv->getDate();
  2814.         $smsDate $date->format('d-m-Y H:i');
  2815.         $locale 'fr_FR';
  2816.         $formatter = new IntlDateFormatter(
  2817.             $locale,
  2818.             IntlDateFormatter::FULL,
  2819.             IntlDateFormatter::SHORT,
  2820.             null,
  2821.             IntlDateFormatter::GREGORIAN,
  2822.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  2823.         );
  2824.         $smsDateLongFormat $formatter->format($date);
  2825.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  2826.         $client->setIdCentre($rdv->getIdCentre());
  2827.         $client->setIdAudio($rdv->getIdAudio());
  2828.         $entityManager->persist($client);
  2829.         $entityManager->flush();
  2830.         // client notif mail Sms
  2831.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  2832.         $frenchDate ucfirst($frenchDate);
  2833.         $responses = [
  2834.             'rangeAge' => isset($data['rangeAge']) ? $data['rangeAge'] : null,
  2835.             'situations' => (isset($data['situations']) && !empty($data['situations'])) ? implode(", "$data['situations']) : null,
  2836.             'equipeAppareil' => isset($data['equipe']) ? $data['equipe'] : null,
  2837.             'durationEquipe' => isset($data['durationEquipe']) ? $data['durationEquipe'] : null,
  2838.             'bilanAuditif' => isset($data['bilanAuditif']) ? $data['bilanAuditif'] : null,
  2839.             'ordonance' => isset($data['ordonnance']) ? $data['ordonnance'] : null,
  2840.             'dateOrdonance' => isset($data['dateOrdonance']) ? $data['dateOrdonance'] : null,
  2841.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  2842.         ];
  2843.         $paramsSourceLead = [
  2844.             'trafficSource' => isset($data['traffic_source']) ? $data['traffic_source'] : null,
  2845.             'articleName' => isset($data['article_name']) ? $data['article_name'] : null,
  2846.             'lpVersion' => isset($data['lp_version']) ? $data['lp_version'] : null,
  2847.         ];
  2848.         $params = array(
  2849.             "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  2850.             "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  2851.             "date" => $smsDateLongFormat,
  2852.             "RdvDate" => $smsDateLongFormat,
  2853.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  2854.             "centerName" => $rdv->getIdCentre()->getName(),
  2855.             "prenom" => $client->getName(),
  2856.             "centerAddress" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  2857.             "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  2858.             'motif' => $rdv->getIdMotif()->getTitre(),
  2859.             "centerCity" => $rdv->getIdCentre()->getCity(),
  2860.             "audioName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  2861.             'titre' => "Votre rendez-vous est validé le " substr($smsDate010) . " à "  substr($smsDate1115),
  2862.             "position" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  2863.             "address" => $rdv->getIdCentre()->getAddress(),
  2864.             "postal" => $rdv->getIdCentre()->getPostale(),
  2865.             "city" => $rdv->getIdCentre()->getCity(),
  2866.             "clientEmail" => $client->getMail(),
  2867.             "clientPassword" => isset($data["passwordGenerated"]) ? $data["passwordGenerated"] : null,
  2868.             "clientAddress" => $client->getAddress(),
  2869.             "clientPostal" => $client->getPostal(),
  2870.             "clientCity" => $client->getCity(),
  2871.             "audioName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  2872.             "frenchDate" => $frenchDate,
  2873.             "heure" => substr($smsDate1115),
  2874.             "centerName" => $rdv->getIdCentre()->getName(),
  2875.             "audioMail" => $rdv->getIdAudio()->getMail(),
  2876.             "modifUrl" => "{$_ENV['BASE_client']}mes-rendez-vous",
  2877.         );
  2878.         $paramsPatient $params;
  2879.         $isNew false;
  2880.         if (isset($data["isLead"]) && isset($data["passwordGenerated"]) != null) {
  2881.             $subject "✅Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  2882.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject189);
  2883.             $isNew true;
  2884.         } else {
  2885.             $subject "Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  2886.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject181);
  2887.         }
  2888.         $sms "Votre RDV est validé le " substr($smsDate010) . " à " substr($smsDate1115) . ", en cas d'imprévu contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
  2889.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  2890.         // audio Notif mail SMS
  2891.         $birthday $rdv->getIdClient()->getBirthdate();
  2892.         $params = array(
  2893.             "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  2894.             "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  2895.             "date" => substr($smsDate010),
  2896.             "heure" => substr($smsDate1115),
  2897.             "mail" => $client->getMail(),
  2898.             "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  2899.             'telClient' => $client->getPhone(),
  2900.             'phone' => $client->getPhone(),
  2901.             'clientCivilite' => $client->getCivilite(),
  2902.             'clientNom' => $client->getLastname(),
  2903.             'clientPrenom' => $client->getName(),
  2904.             'clientPostal' => $client->getPostal(),
  2905.             'clientMail' => $client->getMail(),
  2906.             'clientPhone' => $client->getPhone(),
  2907.             'motif' => $rdv->getIdMotif()->getTitre(),
  2908.             'birthdate' => $client->getBirthdate() ? $client->getBirthdate()->format("d/m/Y") : null,
  2909.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  2910.             'centerName' => $rdv->getIdCentre()->getName(),
  2911.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  2912.             'centerCity' => $rdv->getIdCentre()->getCity(),
  2913.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  2914.             'idPatient' => $client->getId(),
  2915.             'proUrl' => "{$_ENV['BASE_logiciel']}",
  2916.             'frenchDate' => $frenchDate,
  2917.             'responses' => $responses,
  2918.         );
  2919.         $templateEmail 182;
  2920.         if (!empty($data['canMove'])) {
  2921.             $templateEmail 197;
  2922.         }
  2923.         $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  2924.         $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  2925.         if ($rdv->getIdAudio()->getConfirmRdvMail()) {
  2926.             $subject "✅Nouveau Rendez-vous My Audio le " $frenchDate " à " substr($smsDate1115);
  2927.             $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject$templateEmail);
  2928.         }
  2929.         if ($rdv->getIdAudio()->getConfirmRdvSms()) {
  2930.             $sms "Vous avez un nouveau RDV le " substr($smsDate010) . " à " substr($smsDate1115) . ", en cas d'aléas contactez votre patient " $client->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
  2931.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  2932.         }
  2933.         // send notif to admin
  2934.         $paramsAdmin = array(
  2935.             "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  2936.             "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  2937.             "RdvDate" => substr($smsDate010),
  2938.             "heure" => substr($smsDate1115),
  2939.             "clientMail" => $client->getMail(),
  2940.             "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  2941.             'telClient' => $client->getPhone(),
  2942.             'clientNom' => $client->getLastname(),
  2943.             'clientPrenom' => $client->getName(),
  2944.             'clientCivilite' => $client->getCivilite(),
  2945.             'clientPostal' => $client->getPostal(),
  2946.             'clientPhone' => $client->getPhone(),
  2947.             'motif' => $rdv->getIdMotif()->getTitre(),
  2948.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  2949.             'centerName' => $rdv->getIdCentre()->getName(),
  2950.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  2951.             'centerCity' => $rdv->getIdCentre()->getCity(),
  2952.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  2953.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  2954.             'date' => substr($smsDate010),
  2955.             'urlApi' => "{$_ENV['BASE_API']}",
  2956.             'clientId' => $client->getId(),
  2957.             'centerId' => $rdv->getIdCentre()->getId(),
  2958.             'frenchDate' => $frenchDate,
  2959.             'responses' => $responses,
  2960.             'paramsSourceLead' => $paramsSourceLead
  2961.         );
  2962.         $subject "Nouveau RDV MA | RR - " $rdv->getIdCentre()->getName();
  2963.         $templateEmail 183;
  2964.         if (!empty($data['canMove'])) {
  2965.             $templateEmail 190;
  2966.         }
  2967.         if (!isset($data["isLead"])) {
  2968.             $publicFunction->sendEmail($paramsAdmin"lead.myaudio@gmail.com""my audio"$subject$templateEmail);
  2969.         }
  2970.         //$publicFunction->sendEmail($paramsAdmin,"testpation1254@myaudio.fr","my audio", 'Nouveau RDV à My Audio Pro', $templateEmail);
  2971.         $publicFunction->sendEmail($paramsAdmin"contact@myaudio.fr""my audio"$subject$templateEmail);
  2972.         $publicFunction->sendEmail($paramsAdmin"lead.myaudio@gmail.com""my audio"$subject$templateEmail);
  2973.         // google calendar post
  2974.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  2975.             ->findBy(array('audio' => $audio->getId()));
  2976.         $data['rdv'] = $rdv->getId();
  2977.         if (isset($data['clientRdvLp']) && !empty($data['clientRdvLp'])) {
  2978.             $rdvLead $this->entityManager->getRepository(LeadRdv::class)->find($data['clientRdvLp']);
  2979.             if ($rdvLead) {
  2980.                 $leadStatus $this->entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'rdv_valider']);
  2981.                 if ($leadStatus) {
  2982.                     $rdvLead->setLeadStatus($leadStatus);
  2983.                     $rdvLead->setRdv($rdv);
  2984.                     $this->entityManager->flush();
  2985.                 }
  2986.             }
  2987.         }
  2988.         foreach ($synchronisations as $synchronisation) {
  2989.             if (!$synchronisation->getIsDeleted()) {
  2990.                 $googleCalendar->checkAndRefreshAccessToken($synchronisation);
  2991.                 $googleCalendar->createEvent($synchronisation$data);
  2992.             }
  2993.         }
  2994.         if (isset($data["isMyaudio"]) || isset($data["isRdvLead"]) || isset($data["isRdvRapide"])) {
  2995.             try {
  2996.                 $Callservice->handleCallCenterAfterRdv(
  2997.                     $rdv
  2998.                 );
  2999.                 $rdv->setIsNotificationRdvCallSent(1);
  3000.                 $this->entityManager->flush();
  3001.             } catch (\Exception $e) {
  3002.                 $this->logger->error("Erreur lors de l'appel de notification pour le RDV #{$rdv->getId()}: " $e->getMessage());
  3003.             }
  3004.         }
  3005.         $token $this->entityManager
  3006.              ->getRepository(Token::class)
  3007.              ->findOneBy(['token' => $data['token']]);
  3008.         $tokenAudioId $token->getIdAudio()->getId();
  3009.         $requestAudioId $data['audio_id'] ?? null;
  3010.         if ($requestAudioId && $requestAudioId == $tokenAudioId) {
  3011.         // Only publish for this audio
  3012.         $this->mercure->publishRdvUpdate($rdv'created');
  3013.         }
  3014.          // Find the audio/user who owns the referral code
  3015.     $referrer $client// the user who shared the code
  3016.     // Make sure key exists
  3017.     $codeParrain $data['codeParrain'] ?? null;  // null if not provided
  3018.     if ($codeParrain) {
  3019.       // Find the new user/referee who is using the code 
  3020.       $referee $entityManager->getRepository(Client::class)->findOneBy([
  3021.           'referralCode' => $codeParrain
  3022.       ]);
  3023.     if ($referee) {
  3024.         $referral = new Referral();
  3025.         $referral->setReferrerType('patient'); 
  3026.         $referral->setReferrerId($referrer->getId()); 
  3027.         $referral->setRefereeType('patient'); 
  3028.         $referral->setRefereeId($referee->getId()); 
  3029.         $referral->setCodeUsed($codeParrain); 
  3030.         $referral->setStatus('pending');
  3031.         $referral->setRewardAmount(100); 
  3032.         $referral->setCreatedAt(new \DateTime());
  3033.         $entityManager->persist($referral);
  3034.         $entityManager->flush();
  3035.     }
  3036.     }
  3037.         return new Response(json_encode(([
  3038.             "id" => $rdv->getId(),
  3039.             "motif_id" => $rdv->getIdMotif()->getId(),
  3040.             "audio_id" => $rdv->getIdAudio()->getId(),
  3041.             "remplacant_id" => $remplacant_id == -null $remplacant_id,
  3042.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  3043.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  3044.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  3045.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  3046.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  3047.             "testclient" => $rdv->getTestClient() ? [
  3048.                 "result" => $rdv->getTestClient()->getResultTonal(),
  3049.                 "date" => $rdv->getTestClient()->getDate(),
  3050.                 "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  3051.             ] : null,
  3052.             "duration" => $audioMotif->getDuration(),
  3053.             "consigne" => $audioMotif->getConsigne(),
  3054.             "etat_id" => $rdv->getIdEtat()->getId(),
  3055.             "date" => $rdv->getDate(),
  3056.             "comment" => $rdv->getComment(),
  3057.             "centerName" => $rdv->getIdCentre()->getName(),
  3058.             "review" => $rdv->getReview(),
  3059.             "note" => $rdv->getNote(),
  3060.             "status" => 200,
  3061.             "paramsPatient" => $paramsPatient,
  3062.             "isNew" => $isNew,
  3063.         ])));
  3064.     }
  3065.     /**
  3066.      * @Route("/rdv/v2", name="postRdvV2", methods={"POST"})
  3067.      *
  3068.      * Version optimisée de la prise de rendez-vous pour les clients via le site
  3069.      * Gestion complète: validation, création RDV, notifications email/SMS
  3070.      */
  3071.     public function postRdvV2(
  3072.         Request $request,
  3073.         PublicFunction $publicFunction,
  3074.         GoogleCalendarService $googleCalendar,
  3075.         AppointmentCallService $callService
  3076.     ): JsonResponse {
  3077.         try {
  3078.             $data json_decode($request->getContent(), true);
  3079.             // Validation du token et récupération du client
  3080.             $validationResult $this->validateTokenAndGetClient($data);
  3081.             if ($validationResult instanceof Response) {
  3082.                 return new JsonResponse(json_decode($validationResult->getContent(), true), $validationResult->getStatusCode());
  3083.             }
  3084.             ['client' => $client'token' => $token] = $validationResult;
  3085.             // Récupération et validation de l'audio
  3086.             $audio $this->entityManager->getRepository(Audio::class)->find($data['audio_id'] ?? null);
  3087.             if (!$audio) {
  3088.                 return new JsonResponse([
  3089.                     'message' => "Aucun audioprothésiste trouvé avec cet ID.",
  3090.                     'status' => 404
  3091.                 ], 404);
  3092.             }
  3093.             // Vérification du blocage client
  3094.             $clientBlocked $this->entityManager->getRepository(ClientBlocked::class)
  3095.                 ->findOneBy(['id_audio' => $audio'id_client' => $client]);
  3096.             if ($clientBlocked) {
  3097.                 return new JsonResponse([
  3098.                     'message' => 'Vous avez été bloqué par cet audioprothésiste.',
  3099.                     'status' => 403
  3100.                 ], 403);
  3101.             }
  3102.             // Validation du centre/lieu
  3103.             $locationResult $this->validateLocation($data$audio);
  3104.             if ($locationResult instanceof Response) {
  3105.                 return new JsonResponse(json_decode($locationResult->getContent(), true), $locationResult->getStatusCode());
  3106.             }
  3107.             ['centre' => $centre'lieu' => $lieu'liaison' => $liaison] = $locationResult;
  3108.             // Validation du motif
  3109.             $motifResult $this->validateMotif($data$audio);
  3110.             if ($motifResult instanceof Response) {
  3111.                 return new JsonResponse(json_decode($motifResult->getContent(), true), $motifResult->getStatusCode());
  3112.             }
  3113.             ['motif' => $motif'audioMotif' => $audioMotif] = $motifResult;
  3114.             // Validation de la disponibilité
  3115.             $date \DateTime::createFromFormat("d/m/Y H:i"$data['date']);
  3116.             if (!$date) {
  3117.                 return new JsonResponse([
  3118.                     'message' => 'Format de date invalide. Utilisez le format: d/m/Y H:i',
  3119.                     'status' => 400
  3120.                 ], 400);
  3121.             }
  3122.             $availabilityResult $this->validateAvailability(
  3123.                 $audio,
  3124.                 $date,
  3125.                 $audioMotif->getDuration(),
  3126.                 $centre,
  3127.                 $lieu,
  3128.                 $liaison,
  3129.                 $publicFunction
  3130.             );
  3131.             if ($availabilityResult instanceof Response) {
  3132.                 return new JsonResponse(json_decode($availabilityResult->getContent(), true), $availabilityResult->getStatusCode());
  3133.             }
  3134.             $remplacant_id $availabilityResult;
  3135.             // Création du rendez-vous
  3136.             $rdv $this->createAppointment($data$client$audio$centre$lieu$motif$audioMotif$date$remplacant_id);
  3137.             // Envoi des notifications
  3138.             $this->sendNotifications($rdv$client$audio$publicFunction$data);
  3139.             // Synchronisation Google Calendar
  3140.             $this->syncGoogleCalendar($audio$rdv$googleCalendar$data);
  3141.             // Notification call center si nécessaire
  3142.             if (isset($data['isMyaudio']) || isset($data['isRdvLead']) || isset($data['isRdvRapide'])) {
  3143.                 try {
  3144.                     $callService->handleCallCenterAfterRdv($rdv);
  3145.                     $rdv->setIsNotificationRdvCallSent(1);
  3146.                     $this->entityManager->flush();
  3147.                 } catch (\Exception $e) {
  3148.                     $this->logger->error("Erreur notification call center RDV #{$rdv->getId()}: " $e->getMessage());
  3149.                 }
  3150.             }
  3151.             // Réponse finale
  3152.             return new JsonResponse([
  3153.                 'success' => true,
  3154.                 'message' => 'Rendez-vous créé avec succès',
  3155.                 'rdv' => [
  3156.                     'id' => $rdv->getId(),
  3157.                     'date' => $rdv->getDate()->format('d/m/Y H:i'),
  3158.                     'motif' => $motif->getTitre(),
  3159.                     'duration' => $audioMotif->getDuration(),
  3160.                     'centre' => $centre $centre->getName() : null,
  3161.                     'lieu' => $lieu $lieu->getName() : null,
  3162.                     'audio' => $audio->getName() . ' ' $audio->getLastName(),
  3163.                 ],
  3164.                 'status' => 201
  3165.             ], 201);
  3166.         } catch (\Exception $e) {
  3167.             $this->logger->error("Erreur lors de la création du RDV: " $e->getMessage());
  3168.             return new JsonResponse([
  3169.                 'success' => false,
  3170.                 'message' => 'Une erreur est survenue lors de la création du rendez-vous.',
  3171.                 'error' => $e->getMessage(),
  3172.                 'status' => 500
  3173.             ], 500);
  3174.         }
  3175.     }
  3176.     /**
  3177.      * Valide le token et récupère le client associé
  3178.      */
  3179.     private function validateTokenAndGetClient(array $data)
  3180.     {
  3181.         if (!isset($data['token'])) {
  3182.             return new Response(json_encode([
  3183.                 'message' => "Aucun token n'a été spécifié",
  3184.                 'status' => 401
  3185.             ]), 401);
  3186.         }
  3187.         $token $this->entityManager->getRepository(Token::class)
  3188.             ->findOneBy(['token' => $data['token']]);
  3189.         if (!$token) {
  3190.             return new Response(json_encode([
  3191.                 'message' => "Token invalide. Veuillez vous reconnecter.",
  3192.                 'status' => 404
  3193.             ]), 404);
  3194.         }
  3195.         // Vérification de l'âge du token
  3196.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  3197.         if ($dateDiff->7) {
  3198.             $this->entityManager->remove($token);
  3199.             $this->entityManager->flush();
  3200.             return new Response(json_encode([
  3201.                 'message' => 'Token expiré. Veuillez vous reconnecter.',
  3202.                 'status' => 401
  3203.             ]), 401);
  3204.         }
  3205.         // Récupération du client
  3206.         $client $token->getIdClient();
  3207.         if (!$client) {
  3208.             return new Response(json_encode([
  3209.                 'message' => "Ce token n'est pas associé à un client.",
  3210.                 'status' => 400
  3211.             ]), 400);
  3212.         }
  3213.         return ['client' => $client'token' => $token];
  3214.     }
  3215.     /**
  3216.      * Valide le centre ou lieu du rendez-vous
  3217.      */
  3218.     private function validateLocation(array $dataAudio $audio)
  3219.     {
  3220.         $centre null;
  3221.         $lieu null;
  3222.         $liaison null;
  3223.         if (isset($data['centre_id'])) {
  3224.             $centre $this->entityManager->getRepository(Centre::class)->find($data['centre_id']);
  3225.             if (!$centre) {
  3226.                 return new Response(json_encode([
  3227.                     'message' => 'Aucun centre trouvé avec cet ID',
  3228.                     'status' => 404
  3229.                 ]), 404);
  3230.             }
  3231.             $liaison $this->entityManager->getRepository(AudioCentre::class)
  3232.                 ->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
  3233.             if (!$liaison) {
  3234.                 return new Response(json_encode([
  3235.                     'message' => "L'audioprothésiste n'est pas rattaché à ce centre",
  3236.                     'status' => 400
  3237.                 ]), 400);
  3238.             }
  3239.         } elseif (isset($data['lieu_id']) && $audio->getIsIndie()) {
  3240.             $lieu $this->entityManager->getRepository(Lieu::class)
  3241.                 ->findOneBy(['id' => $data['lieu_id'], 'id_gerant' => $audio->getId()]);
  3242.             if (!$lieu) {
  3243.                 return new Response(json_encode([
  3244.                     'message' => 'Aucun lieu trouvé avec cet ID',
  3245.                     'status' => 404
  3246.                 ]), 404);
  3247.             }
  3248.         } else {
  3249.             return new Response(json_encode([
  3250.                 'message' => 'Veuillez spécifier un centre ou un lieu',
  3251.                 'status' => 400
  3252.             ]), 400);
  3253.         }
  3254.         return ['centre' => $centre'lieu' => $lieu'liaison' => $liaison];
  3255.     }
  3256.     /**
  3257.      * Valide le motif du rendez-vous
  3258.      */
  3259.     private function validateMotif(array $dataAudio $audio)
  3260.     {
  3261.         if (!isset($data['motif_id'])) {
  3262.             return new Response(json_encode([
  3263.                 'message' => 'Aucun motif spécifié',
  3264.                 'status' => 400
  3265.             ]), 400);
  3266.         }
  3267.         $motif $this->entityManager->getRepository(Motif::class)->find($data['motif_id']);
  3268.         if (!$motif) {
  3269.             return new Response(json_encode([
  3270.                 'message' => 'Aucun motif trouvé avec cet ID',
  3271.                 'status' => 404
  3272.             ]), 404);
  3273.         }
  3274.         $audioMotif $this->entityManager->getRepository(AudioMotif::class)
  3275.             ->findOneBy(['id_audio' => $audio->getId(), 'id_motif' => $data['motif_id']]);
  3276.         if (!$audioMotif) {
  3277.             return new Response(json_encode([
  3278.                 'message' => "Ce motif n'est pas disponible pour cet audioprothésiste",
  3279.                 'status' => 400
  3280.             ]), 400);
  3281.         }
  3282.         return ['motif' => $motif'audioMotif' => $audioMotif];
  3283.     }
  3284.     /**
  3285.      * Valide la disponibilité du créneau
  3286.      */
  3287.     private function validateAvailability(
  3288.         Audio $audio,
  3289.         \DateTime $date,
  3290.         int $duration,
  3291.         ?Centre $centre,
  3292.         ?Lieu $lieu,
  3293.         ?AudioCentre $liaison,
  3294.         PublicFunction $publicFunction
  3295.     ) {
  3296.         // Vérification qu'il n'y a pas déjà un RDV à cette date
  3297.         $existingRdv $this->entityManager->getRepository(Rdv::class)
  3298.             ->findOneBy([
  3299.                 'date' => $date,
  3300.                 'id_audio' => $audio,
  3301.                 'id_centre' => $centre,
  3302.                 'id_lieu' => $lieu,
  3303.             ]);
  3304.         if ($existingRdv) {
  3305.             return new Response(json_encode([
  3306.                 'message' => 'Un rendez-vous existe déjà à ce créneau',
  3307.                 'status' => 409
  3308.             ]), 409);
  3309.         }
  3310.         // Vérification de la disponibilité selon le type d'audio
  3311.         if ($audio->getIsIndie()) {
  3312.             if ($centre && $liaison) {
  3313.                 if (!$liaison->getHoraire() || $liaison->getHoraire() == []) {
  3314.                     return new Response(json_encode([
  3315.                         'message' => 'Aucun horaire configuré pour cet audioprothésiste',
  3316.                         'status' => 400
  3317.                     ]), 400);
  3318.                 }
  3319.                 if (!$publicFunction->calculScheduleFitDate($audio$date$duration$centre)) {
  3320.                     return new Response(json_encode([
  3321.                         'message' => 'Créneau non disponible',
  3322.                         'status' => 400
  3323.                     ]), 400);
  3324.                 }
  3325.                 return $publicFunction->checkIfRemplacant($liaison->getHoraire(), $date);
  3326.             } else {
  3327.                 if (!$lieu->getHoraire() || $lieu->getHoraire() == []) {
  3328.                     return new Response(json_encode([
  3329.                         'message' => 'Aucun horaire configuré pour ce lieu',
  3330.                         'status' => 400
  3331.                     ]), 400);
  3332.                 }
  3333.                 if (!$publicFunction->calculScheduleFitDate($audio$date$durationnull$lieu)) {
  3334.                     return new Response(json_encode([
  3335.                         'message' => 'Créneau non disponible',
  3336.                         'status' => 400
  3337.                     ]), 400);
  3338.                 }
  3339.                 return $publicFunction->checkIfRemplacant($lieu->getHoraire(), $date);
  3340.             }
  3341.         } else {
  3342.             if (!$liaison || !$liaison->getHoraire() || $liaison->getHoraire() == []) {
  3343.                 return new Response(json_encode([
  3344.                     'message' => 'Aucun horaire configuré',
  3345.                     'status' => 400
  3346.                 ]), 400);
  3347.             }
  3348.             return $publicFunction->checkIfRemplacant($liaison->getHoraire(), $date);
  3349.         }
  3350.     }
  3351.     /**
  3352.      * Crée le rendez-vous en base de données
  3353.      */
  3354.     private function createAppointment(
  3355.         array $data,
  3356.         Client $client,
  3357.         Audio $audio,
  3358.         ?Centre $centre,
  3359.         ?Lieu $lieu,
  3360.         Motif $motif,
  3361.         AudioMotif $audioMotif,
  3362.         \DateTime $date,
  3363.         int $remplacant_id
  3364.     ): Rdv {
  3365.         $rdv = new Rdv();
  3366.         $rdv->setIdClient($client);
  3367.         $rdv->setIdAudio($audio);
  3368.         $rdv->setIdCentre($centre);
  3369.         $rdv->setIdLieu($lieu);
  3370.         $rdv->setIdMotif($motif);
  3371.         $rdv->setDate($date);
  3372.         $rdv->setDateCreation(new \DateTime());
  3373.         // Toujours mettre isMyaudio à true pour les RDV clients via le site
  3374.         $rdv->setIsMyaudio(true);
  3375.         $rdv->setIsRdvLp(isset($data['isRdvLead']));
  3376.         $rdv->setIsRdvRapide(isset($data['isRdvRapide']));
  3377.         $rdv->setIsAbsence(0);
  3378.         $rdv->setCacher(0);
  3379.         // Récupération du dernier test client si disponible
  3380.         $testClient $this->entityManager->getRepository(TestClient::class)
  3381.             ->getLatestTestClient($client);
  3382.         if ($testClient && !$testClient->getRdv()) {
  3383.             $rdv->setTestClient($testClient);
  3384.         }
  3385.         // Gestion proche si spécifié
  3386.         if (isset($data['proche_id'])) {
  3387.             $proche $this->entityManager->getRepository(Proches::class)
  3388.                 ->findOneBy(['id' => $data['proche_id'], 'id_client' => $client]);
  3389.             if ($proche) {
  3390.                 $rdv->setIdProche($proche);
  3391.             }
  3392.         }
  3393.         // Durée : utilise celle du motif par défaut ou celle fournie dans les données
  3394.         $rdv->setDuration($data['duree'] ?? $audioMotif->getDuration());
  3395.         // Couleur personnalisée
  3396.         if (isset($data['color'])) {
  3397.             $rdv->setColor($data['color']);
  3398.         }
  3399.         // Note
  3400.         if (isset($data['note'])) {
  3401.             $rdv->setNote($data['note']);
  3402.         }
  3403.         // État du rendez-vous
  3404.         $etat $this->entityManager->getRepository(EtatRdv::class)
  3405.             ->find($data['etat_id'] ?? 1); // État par défaut : 1
  3406.         if ($etat) {
  3407.             $rdv->setIdEtat($etat);
  3408.         }
  3409.         // Remplaçant si applicable
  3410.         if ($remplacant_id != -1) {
  3411.             $remplacant $this->entityManager->getRepository(Remplacant::class)->find($remplacant_id);
  3412.             if ($remplacant) {
  3413.                 $rdv->setRemplacant($remplacant);
  3414.             }
  3415.         }
  3416.         // Gestion lead
  3417.         if (isset($data['lead'])) {
  3418.             $lead $this->entityManager->getRepository(LeadRdv::class)->find($data['lead']);
  3419.             if ($lead) {
  3420.                 $lead->setRdv($rdv);
  3421.                 $leadStatus $this->entityManager->getRepository(LeadStatus::class)
  3422.                     ->findOneBy(['slug' => 'rdv_valider']);
  3423.                 if ($leadStatus) {
  3424.                     $lead->setLeadStatus($leadStatus);
  3425.                 }
  3426.             }
  3427.         }
  3428.         // Mise à jour du client avec centre et audio
  3429.         $client->setIdCentre($centre);
  3430.         $client->setIdAudio($audio);
  3431.         $this->entityManager->persist($client);
  3432.         $this->entityManager->persist($rdv);
  3433.         $this->entityManager->flush();
  3434.         return $rdv;
  3435.     }
  3436.     /**
  3437.      * Envoie toutes les notifications (email + SMS) au client, audio et admin
  3438.      */
  3439.     private function sendNotifications(Rdv $rdvClient $clientAudio $audioPublicFunction $publicFunction, array $data): void
  3440.     {
  3441.         $date $rdv->getDate();
  3442.         $smsDate $date->format('d-m-Y H:i');
  3443.         $formatter = new IntlDateFormatter(
  3444.             'fr_FR',
  3445.             IntlDateFormatter::FULL,
  3446.             IntlDateFormatter::SHORT,
  3447.             null,
  3448.             IntlDateFormatter::GREGORIAN,
  3449.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  3450.         );
  3451.         $smsDateLongFormat $formatter->format($date);
  3452.         $frenchDate ucfirst(preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat));
  3453.         // === Notification CLIENT ===
  3454.         $this->sendClientNotification($rdv$client$smsDate$smsDateLongFormat$frenchDate$publicFunction$data);
  3455.         // === Notification AUDIO ===
  3456.         if ($audio->getConfirmRdvMail() || $audio->getConfirmRdvSms()) {
  3457.             $this->sendAudioNotification($rdv$client$audio$smsDate$frenchDate$publicFunction$data);
  3458.         }
  3459.         // === Notification ADMIN ===
  3460.         $this->sendAdminNotification($rdv$client$smsDate$frenchDate$publicFunction$data);
  3461.     }
  3462.     /**
  3463.      * Envoie les notifications au client (email + SMS)
  3464.      */
  3465.     private function sendClientNotification(
  3466.         Rdv $rdv,
  3467.         Client $client,
  3468.         string $smsDate,
  3469.         string $smsDateLongFormat,
  3470.         string $frenchDate,
  3471.         PublicFunction $publicFunction,
  3472.         array $data
  3473.     ): void {
  3474.         $centre $rdv->getIdCentre();
  3475.         $params = [
  3476.             'lienModifer' => $_ENV['BASE_client'] . 'mes-rendez-vous',
  3477.             'lienAnnule' => $_ENV['BASE_client'] . 'mes-rendez-vous',
  3478.             'date' => $smsDateLongFormat,
  3479.             'RdvDate' => $smsDateLongFormat,
  3480.             'telCentre' => $centre->getPhone(),
  3481.             'centerName' => $centre->getName(),
  3482.             'prenom' => $client->getName(),
  3483.             'centerAddress' => $centre->getAddress() . ' ' $centre->getPostale() . ' ' $centre->getCity(),
  3484.             'centerPostalCode' => $centre->getPostale(),
  3485.             'motif' => $rdv->getIdMotif()->getTitre(),
  3486.             'centerCity' => $centre->getCity(),
  3487.             'audioName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  3488.             'titre' => 'Votre rendez-vous est validé le ' substr($smsDate010) . ' à ' substr($smsDate1115),
  3489.             'frenchDate' => $frenchDate,
  3490.             'heure' => substr($smsDate1115),
  3491.             'clientEmail' => $client->getMail(),
  3492.             'clientPassword' => $data['passwordGenerated'] ?? null,
  3493.             'modifUrl' => $_ENV['BASE_client'] . 'mes-rendez-vous',
  3494.         ];
  3495.         // Email client
  3496.         $templateId = (isset($data['isLead']) && isset($data['passwordGenerated'])) ? 189 181;
  3497.         $subject '✅ Rendez-vous My Audio confirmé le ' $smsDateLongFormat;
  3498.         $publicFunction->sendEmail(
  3499.             $params,
  3500.             $client->getMail(),
  3501.             $client->getName() . ' ' $client->getLastName(),
  3502.             $subject,
  3503.             $templateId
  3504.         );
  3505.         // SMS client
  3506.         $smsMessage "Votre RDV est validé le " substr($smsDate010) . " à " substr($smsDate1115) .
  3507.                       ", en cas d'imprévu contactez votre centre " $centre->getPhone() .
  3508.                       " pour modifier votre consultation.\nNe pas répondre.";
  3509.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$smsMessage$client->getPhone());
  3510.     }
  3511.     /**
  3512.      * Envoie les notifications à l'audioprothésiste (email + SMS)
  3513.      */
  3514.     private function sendAudioNotification(
  3515.         Rdv $rdv,
  3516.         Client $client,
  3517.         Audio $audio,
  3518.         string $smsDate,
  3519.         string $frenchDate,
  3520.         PublicFunction $publicFunction,
  3521.         array $data
  3522.     ): void {
  3523.         $responses = [
  3524.             'rangeAge' => $data['rangeAge'] ?? null,
  3525.             'situations' => (isset($data['situations']) && !empty($data['situations'])) ? implode(", "$data['situations']) : null,
  3526.             'equipeAppareil' => $data['equipe'] ?? null,
  3527.             'durationEquipe' => $data['durationEquipe'] ?? null,
  3528.             'bilanAuditif' => $data['bilanAuditif'] ?? null,
  3529.             'ordonance' => $data['ordonnance'] ?? null,
  3530.             'dateOrdonance' => $data['dateOrdonance'] ?? null,
  3531.             'canMove' => $data['canMove'] ?? null,
  3532.         ];
  3533.         $params = [
  3534.             'lienModifer' => $_ENV['BASE_logiciel'] . 'rdv',
  3535.             'lienAnnule' => $_ENV['BASE_logiciel'] . 'rdv',
  3536.             'date' => substr($smsDate010),
  3537.             'heure' => substr($smsDate1115),
  3538.             'audioproName' => $audio->getCivilite() . ' ' $audio->getName() . ' ' $audio->getLastName(),
  3539.             'phone' => $client->getPhone(),
  3540.             'clientCivilite' => $client->getCivilite(),
  3541.             'clientNom' => $client->getLastname(),
  3542.             'clientPrenom' => $client->getName(),
  3543.             'clientPostal' => $client->getPostal(),
  3544.             'clientMail' => $client->getMail(),
  3545.             'clientPhone' => $client->getPhone(),
  3546.             'motif' => $rdv->getIdMotif()->getTitre(),
  3547.             'birthdate' => $client->getBirthdate() ? $client->getBirthdate()->format("d/m/Y") : null,
  3548.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  3549.             'centerName' => $rdv->getIdCentre()->getName(),
  3550.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  3551.             'centerCity' => $rdv->getIdCentre()->getCity(),
  3552.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  3553.             'idPatient' => $client->getId(),
  3554.             'proUrl' => $_ENV['BASE_logiciel'],
  3555.             'frenchDate' => $frenchDate,
  3556.             'responses' => $responses,
  3557.         ];
  3558.         $templateEmail = !empty($data['canMove']) ? 197 182;
  3559.         $mailAudio $audio->getMailNotif() ?? $audio->getMail();
  3560.         $phoneAudio $audio->getPhoneNotif() ?? $audio->getPhone();
  3561.         // Email audio
  3562.         if ($audio->getConfirmRdvMail()) {
  3563.             $subject '✅ Nouveau Rendez-vous My Audio le ' $frenchDate ' à ' substr($smsDate1115);
  3564.             $publicFunction->sendEmail($params$mailAudio$audio->getName() . ' ' $audio->getLastName(), $subject$templateEmail);
  3565.         }
  3566.         // SMS audio
  3567.         if ($audio->getConfirmRdvSms()) {
  3568.             $smsMessage "Vous avez un nouveau RDV le " substr($smsDate010) . " à " substr($smsDate1115) .
  3569.                           ", en cas d'aléas contactez votre patient " $client->getPhone() .
  3570.                           " pour modifier votre consultation.\nNe pas répondre.";
  3571.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$smsMessage$phoneAudio);
  3572.         }
  3573.     }
  3574.     /**
  3575.      * Envoie les notifications à l'admin
  3576.      */
  3577.     private function sendAdminNotification(
  3578.         Rdv $rdv,
  3579.         Client $client,
  3580.         string $smsDate,
  3581.         string $frenchDate,
  3582.         PublicFunction $publicFunction,
  3583.         array $data
  3584.     ): void {
  3585.         $responses = [
  3586.             'rangeAge' => $data['rangeAge'] ?? null,
  3587.             'situations' => (isset($data['situations']) && !empty($data['situations'])) ? implode(", "$data['situations']) : null,
  3588.             'equipeAppareil' => $data['equipe'] ?? null,
  3589.             'durationEquipe' => $data['durationEquipe'] ?? null,
  3590.             'bilanAuditif' => $data['bilanAuditif'] ?? null,
  3591.             'ordonance' => $data['ordonnance'] ?? null,
  3592.             'dateOrdonance' => $data['dateOrdonance'] ?? null,
  3593.             'canMove' => $data['canMove'] ?? null,
  3594.         ];
  3595.         $paramsSourceLead = [
  3596.             'trafficSource' => $data['traffic_source'] ?? null,
  3597.             'articleName' => $data['article_name'] ?? null,
  3598.             'lpVersion' => $data['lp_version'] ?? null,
  3599.         ];
  3600.         $paramsAdmin = [
  3601.             'lienModifer' => $_ENV['BASE_logiciel'] . 'rdv',
  3602.             'lienAnnule' => $_ENV['BASE_logiciel'] . 'rdv',
  3603.             'RdvDate' => substr($smsDate010),
  3604.             'heure' => substr($smsDate1115),
  3605.             'clientMail' => $client->getMail(),
  3606.             'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  3607.             'telClient' => $client->getPhone(),
  3608.             'clientNom' => $client->getLastname(),
  3609.             'clientPrenom' => $client->getName(),
  3610.             'clientCivilite' => $client->getCivilite(),
  3611.             'clientPostal' => $client->getPostal(),
  3612.             'clientPhone' => $client->getPhone(),
  3613.             'motif' => $rdv->getIdMotif()->getTitre(),
  3614.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  3615.             'centerName' => $rdv->getIdCentre()->getName(),
  3616.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  3617.             'centerCity' => $rdv->getIdCentre()->getCity(),
  3618.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  3619.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  3620.             'date' => substr($smsDate010),
  3621.             'urlApi' => $_ENV['BASE_API'],
  3622.             'clientId' => $client->getId(),
  3623.             'centerId' => $rdv->getIdCentre()->getId(),
  3624.             'frenchDate' => $frenchDate,
  3625.             'responses' => $responses,
  3626.             'paramsSourceLead' => $paramsSourceLead,
  3627.         ];
  3628.         $subject 'Nouveau RDV MA | RR - ' $rdv->getIdCentre()->getName();
  3629.         $templateEmail = !empty($data['canMove']) ? 190 183;
  3630.         if (!isset($data['isLead'])) {
  3631.             $publicFunction->sendEmail($paramsAdmin'lead.myaudio@gmail.com''my audio'$subject$templateEmail);
  3632.         }
  3633.         $publicFunction->sendEmail($paramsAdmin'contact@myaudio.fr''my audio'$subject$templateEmail);
  3634.     }
  3635.     /**
  3636.      * Synchronise le rendez-vous avec Google Calendar
  3637.      */
  3638.     private function syncGoogleCalendar(Audio $audioRdv $rdvGoogleCalendarService $googleCalendar, array $data): void
  3639.     {
  3640.         try {
  3641.             $synchronisations $this->entityManager->getRepository(SynchronisationSetting::class)
  3642.                 ->findBy(['audio' => $audio->getId()]);
  3643.             $data['rdv'] = $rdv->getId();
  3644.             foreach ($synchronisations as $synchronisation) {
  3645.                 if (!$synchronisation->getIsDeleted()) {
  3646.                     $googleCalendar->checkAndRefreshAccessToken($synchronisation);
  3647.                     $googleCalendar->createEvent($synchronisation$data);
  3648.                 }
  3649.             }
  3650.         } catch (\Exception $e) {
  3651.             $this->logger->error("Erreur synchronisation Google Calendar pour RDV #{$rdv->getId()}: " $e->getMessage());
  3652.         }
  3653.     }
  3654.     /**
  3655.      * @Route("/rdv/{id}/v2", name="getRdvByIDV2", methods={"GET"})
  3656.      *
  3657.      * Version optimisée de getRdvByID
  3658.      * Retourne les informations complètes d'un rendez-vous
  3659.      */
  3660.     public function getRdvByIDV2(int $idRequest $requestPublicFunction $publicFunction): JsonResponse
  3661.     {
  3662.         try {
  3663.             // Validation du token
  3664.             $token $request->query->get('token');
  3665.             if (!$token) {
  3666.                 return new JsonResponse([
  3667.                     'message' => "Aucun token n'a été spécifié",
  3668.                     'status' => 401
  3669.                 ], 401);
  3670.             }
  3671.             $tokenEntity $this->entityManager->getRepository(Token::class)
  3672.                 ->findOneBy(['token' => $token]);
  3673.             if (!$tokenEntity) {
  3674.                 return new JsonResponse([
  3675.                     'message' => "Token invalide. Veuillez vous reconnecter.",
  3676.                     'status' => 404
  3677.                 ], 404);
  3678.             }
  3679.             // Vérification de l'âge du token
  3680.             $dateDiff $tokenEntity->getCreationDate()->diff(new DateTime());
  3681.             if ($dateDiff->7) {
  3682.                 $this->entityManager->remove($tokenEntity);
  3683.                 $this->entityManager->flush();
  3684.                 return new JsonResponse([
  3685.                     'message' => 'Token expiré. Veuillez vous reconnecter.',
  3686.                     'status' => 401
  3687.                 ], 401);
  3688.             }
  3689.             // Récupération du RDV
  3690.             $rdv $this->entityManager->getRepository(Rdv::class)->find($id);
  3691.             if (!$rdv) {
  3692.                 return new JsonResponse([
  3693.                     'message' => "Aucun rendez-vous trouvé avec cet ID",
  3694.                     'status' => 404
  3695.                 ], 404);
  3696.             }
  3697.             // Vérification des droits d'accès
  3698.             $client $tokenEntity->getIdClient();
  3699.             $audio $tokenEntity->getIdAudio();
  3700.             if ($rdv->getIdClient() != $client && $rdv->getIdAudio() != $audio) {
  3701.                 return new JsonResponse([
  3702.                     'message' => "Vous n'êtes pas autorisé à consulter ce rendez-vous",
  3703.                     'status' => 403
  3704.                 ], 403);
  3705.             }
  3706.             // Construction de la réponse
  3707.             $response $this->buildRdvResponse($rdv$publicFunction);
  3708.             return new JsonResponse([
  3709.                 'success' => true,
  3710.                 'rdv' => $response,
  3711.                 'status' => 200
  3712.             ], 200);
  3713.         } catch (\Exception $e) {
  3714.             $this->logger->error("Erreur lors de la récupération du RDV #{$id}: " $e->getMessage());
  3715.             return new JsonResponse([
  3716.                 'success' => false,
  3717.                 'message' => 'Une erreur est survenue lors de la récupération du rendez-vous.',
  3718.                 'error' => $e->getMessage(),
  3719.                 'status' => 500
  3720.             ], 500);
  3721.         }
  3722.     }
  3723.     /**
  3724.      * Construit la réponse complète pour un rendez-vous
  3725.      */
  3726.     private function buildRdvResponse(Rdv $rdvPublicFunction $publicFunction): array
  3727.     {
  3728.         $rdvCentre $rdv->getIdLieu() ?: $rdv->getIdCentre();
  3729.         $audio $rdv->getIdAudio();
  3730.         $centre $rdv->getIdCentre();
  3731.         // Récupération de la liaison audio-centre
  3732.         $liaison null;
  3733.         if ($centre) {
  3734.             $liaison $this->entityManager->getRepository(AudioCentre::class)
  3735.                 ->findOneBy(['id_audio' => $audio'id_centre' => $centre'isConfirmed' => true]);
  3736.         }
  3737.         // Informations de base du RDV
  3738.         $rdvData = [
  3739.             'id' => $rdv->getId(),
  3740.             'date' => $rdv->getDate()->format('Y-m-d H:i:s'),
  3741.             'dateCreation' => $rdv->getDateCreation() ? $rdv->getDateCreation()->format('Y-m-d H:i:s') : null,
  3742.             'duration' => $rdv->getDuration(),
  3743.             'note' => $rdv->getNote(),
  3744.             'comment' => $rdv->getComment(),
  3745.             'review' => $rdv->getReview(),
  3746.             'isMyaudio' => $rdv->getIsMyaudio(),
  3747.             'isRdvLp' => $rdv->getIsRdvLp(),
  3748.             'isRdvRapide' => $rdv->getIsRdvRapide(),
  3749.             'isAbsence' => $rdv->getIsAbsence(),
  3750.             'motif' => [
  3751.                 'id' => $rdv->getIdMotif()->getId(),
  3752.                 'titre' => $rdv->getIdMotif()->getTitre(),
  3753.             ],
  3754.             'etat' => [
  3755.                 'id' => $rdv->getIdEtat()->getId(),
  3756.                 'libelle' => $rdv->getIdEtat()->getLibelle(),
  3757.             ],
  3758.             'client' => $this->buildClientData($rdv),
  3759.             'proche' => $rdv->getIdProche() ? [
  3760.                 'id' => $rdv->getIdProche()->getId(),
  3761.                 'name' => $rdv->getIdProche()->getName(),
  3762.                 'lastname' => $rdv->getIdProche()->getLastname(),
  3763.             ] : null,
  3764.             'testClient' => $rdv->getTestClient() ? [
  3765.                 'result' => $rdv->getTestClient()->getResultTonal(),
  3766.                 'date' => $rdv->getTestClient()->getDate()->format('Y-m-d H:i:s'),
  3767.                 'device' => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  3768.             ] : null,
  3769.             'audio' => $this->buildAudioData($rdv$publicFunction),
  3770.             'centre' => $this->buildCentreData($rdv$rdvCentre$liaison$publicFunction),
  3771.             'remplacant' => $rdv->getRemplacant() ? [
  3772.                 'id' => $rdv->getRemplacant()->getId(),
  3773.                 'civilite' => $rdv->getRemplacant()->getCivilite(),
  3774.                 'name' => $rdv->getRemplacant()->getName(),
  3775.                 'lastname' => $rdv->getRemplacant()->getLastname(),
  3776.                 'imgUrl' => $rdv->getRemplacant()->getImgUrl(),
  3777.             ] : null,
  3778.         ];
  3779.         return $rdvData;
  3780.     }
  3781.     /**
  3782.      * Construit les données du client
  3783.      */
  3784.     private function buildClientData(Rdv $rdv): ?array
  3785.     {
  3786.         $client $rdv->getIdClient() ?: $rdv->getIdClientTemp();
  3787.         if (!$client) {
  3788.             return null;
  3789.         }
  3790.         return [
  3791.             'id' => $client->getId(),
  3792.             'civilite' => $client->getCivilite(),
  3793.             'name' => $client->getName(),
  3794.             'lastname' => $client->getLastname(),
  3795.             'mail' => $client->getMail(),
  3796.             'phone' => $client->getPhone(),
  3797.             'address' => $client->getAddress(),
  3798.             'postal' => $client->getPostal(),
  3799.             'city' => $client->getCity(),
  3800.             'birthdate' => $client->getBirthdate() ? $client->getBirthdate()->format('Y-m-d') : null,
  3801.         ];
  3802.     }
  3803.     /**
  3804.      * Construit les données de l'audio
  3805.      */
  3806.     private function buildAudioData(Rdv $rdvPublicFunction $publicFunction): array
  3807.     {
  3808.         $audio $rdv->getIdAudio();
  3809.         $remplacant $rdv->getRemplacant();
  3810.         // Récupération des reviews audio
  3811.         $audioRdvs $this->entityManager->getRepository(Rdv::class)
  3812.             ->findBy(['id_audio' => $audio->getId()]);
  3813.         $reviewsAudio array_filter($audioRdvs, function($r) {
  3814.             return $r->getReview() !== null && $r->getComment() !== null;
  3815.         });
  3816.         // Motifs
  3817.         $motifs $this->entityManager->getRepository(AudioMotif::class)
  3818.             ->findBy(['id_audio' => $audio->getId()]);
  3819.         $motifsData array_map(function($motif) {
  3820.             return [
  3821.                 'id' => $motif->getIdMotif()->getId(),
  3822.                 'titre' => $motif->getIdMotif()->getTitre(),
  3823.                 'consigne' => $motif->getConsigne(),
  3824.                 'duration' => $motif->getDuration(),
  3825.             ];
  3826.         }, $motifs);
  3827.         // Spécialités
  3828.         $specialities $this->entityManager->getRepository(AudioSpecialite::class)
  3829.             ->findBy(['id_audio' => $audio->getId()]);
  3830.         $specialitiesData array_map(function($spec) {
  3831.             return [
  3832.                 'id' => $spec->getIdSpecialite()->getId(),
  3833.                 'titre' => $spec->getIdSpecialite()->getLibelle(),
  3834.             ];
  3835.         }, $specialities);
  3836.         return [
  3837.             'id' => $remplacant $remplacant->getId() : $audio->getId(),
  3838.             'civilite' => $remplacant $remplacant->getCivilite() : $audio->getCivilite(),
  3839.             'name' => $remplacant $remplacant->getName() : $audio->getName(),
  3840.             'lastname' => $remplacant $remplacant->getLastname() : $audio->getLastname(),
  3841.             'imgUrl' => $remplacant $remplacant->getImgUrl() : $audio->getImgUrl(),
  3842.             'mail' => $remplacant $remplacant->getMail() : $audio->getMail(),
  3843.             'phone' => $remplacant $remplacant->getPhone() : $audio->getPhone(),
  3844.             'adeli' => $audio->getAdeli(),
  3845.             'pin' => $audio->getPin(),
  3846.             'description' => $audio->getDescription(),
  3847.             'averageRating' => $publicFunction->calculateRating($reviewsAudio),
  3848.             'nbrReview' => count($reviewsAudio),
  3849.             'motifs' => array_values($motifsData),
  3850.             'specialities' => array_values($specialitiesData),
  3851.         ];
  3852.     }
  3853.     /**
  3854.      * Construit les données du centre
  3855.      */
  3856.     private function buildCentreData(Rdv $rdv$rdvCentre, ?AudioCentre $liaisonPublicFunction $publicFunction): array
  3857.     {
  3858.         // Récupération des reviews centre
  3859.         $centreRdvs $this->entityManager->getRepository(Rdv::class)
  3860.             ->findBy($rdv->getIdCentre() ? ['id_centre' => $rdvCentre->getId()] : ['id_lieu' => $rdvCentre->getId()]);
  3861.         $reviewsCentre array_filter($centreRdvs, function($r) {
  3862.             return $r->getReview() !== null && $r->getComment() !== null;
  3863.         });
  3864.         // Accès centre
  3865.         $accessCentre $this->entityManager->getRepository(AccessCentre::class)
  3866.             ->findOneBy($rdv->getIdCentre() ? ['id_centre' => $rdvCentre] : ['id_lieu' => $rdvCentre]);
  3867.         // Prestations
  3868.         if ($rdv->getIdCentre()) {
  3869.             $prestations $this->entityManager->getRepository(CentrePrestation::class)
  3870.                 ->findBy(['id_centre' => $rdvCentre->getId()]);
  3871.         } else {
  3872.             $prestations $this->entityManager->getRepository(LieuPrestation::class)
  3873.                 ->findBy(['id_lieu' => $rdvCentre]);
  3874.         }
  3875.         $prestationsData array_map(function($prest) {
  3876.             return [
  3877.                 'id' => $prest->getIdPrestation()->getId(),
  3878.                 'titre' => $prest->getIdPrestation()->getLibelle(),
  3879.             ];
  3880.         }, $prestations);
  3881.         // Mutuelles (uniquement pour centres)
  3882.         $mutuellesData = [];
  3883.         if ($rdv->getIdCentre()) {
  3884.             $mutuelles $this->entityManager->getRepository(CentreMutuelle::class)
  3885.                 ->findBy(['id_centre' => $rdvCentre]);
  3886.             $mutuellesData array_map(function($mut) {
  3887.                 return [
  3888.                     'id' => $mut->getIdMutuelle()->getId(),
  3889.                     'titre' => $mut->getIdMutuelle()->getLibelle(),
  3890.                 ];
  3891.             }, $mutuelles);
  3892.         }
  3893.         // Tiers
  3894.         if ($rdv->getIdCentre()) {
  3895.             $tiers $this->entityManager->getRepository(CentreTier::class)
  3896.                 ->findBy(['id_centre' => $rdvCentre->getId()]);
  3897.         } else {
  3898.             $tiers $this->entityManager->getRepository(LieuTier::class)
  3899.                 ->findBy(['id_lieu' => $rdvCentre]);
  3900.         }
  3901.         $tiersData array_map(function($tier) {
  3902.             return [
  3903.                 'id' => $tier->getIdTier()->getId(),
  3904.                 'titre' => $tier->getIdTier()->getLibelle(),
  3905.             ];
  3906.         }, $tiers);
  3907.         // Horaire
  3908.         $schedule null;
  3909.         if ($rdv->getIdAudio()->getIsIndie() == false) {
  3910.             $schedule $rdv->getIdCentre() ? $rdv->getIdCentre()->getHoraire() : null;
  3911.         } else {
  3912.             $schedule $rdv->getIdLieu() ? $rdv->getIdLieu()->getHoraire() : ($liaison $liaison->getHoraire() : null);
  3913.         }
  3914.         return [
  3915.             'id' => $rdvCentre->getId(),
  3916.             'audio_id' => $rdvCentre->getIdGerant()->getId(),
  3917.             'name' => $rdvCentre->getName(),
  3918.             'imgUrl' => $rdvCentre->getImgUrl(),
  3919.             'isRdvDomicile' => $rdv->getIdCentre() ? $rdvCentre->getIsRdvDomicile() : $rdv->getIdAudio()->getIsRdvDomicileIndie(),
  3920.             'address' => $rdvCentre->getAddress(),
  3921.             'postal' => $rdvCentre->getPostale(),
  3922.             'city' => $rdvCentre->getCity(),
  3923.             'finess' => $rdvCentre->getFiness(),
  3924.             'siret' => $rdvCentre->getSiret(),
  3925.             'website' => $rdvCentre->getWebsite(),
  3926.             'phone' => $rdvCentre->getPhone(),
  3927.             'isHandicap' => $rdvCentre->getIsHandicap(),
  3928.             'longitude' => $rdvCentre->getLongitude(),
  3929.             'latitude' => $rdvCentre->getLatitude(),
  3930.             'description' => $rdv->getIdCentre() ? $rdv->getIdCentre()->getDescription() : null,
  3931.             'averageRating' => $publicFunction->calculateRating($reviewsCentre),
  3932.             'nbrReview' => count($reviewsCentre),
  3933.             'isLieu' => $rdv->getIdLieu() !== null,
  3934.             'schedule' => $schedule,
  3935.             'access' => $accessCentre ? [
  3936.                 'tram' => $accessCentre->getTram(),
  3937.                 'rer' => $accessCentre->getRer(),
  3938.                 'metro' => $accessCentre->getMetro(),
  3939.                 'bus' => $accessCentre->getBus(),
  3940.                 'parkingPublic' => $accessCentre->getParkingPublic(),
  3941.                 'parkingPrivate' => $accessCentre->getParkingPrivate(),
  3942.                 'other' => $accessCentre->getOther(),
  3943.             ] : null,
  3944.             'prestations' => array_values($prestationsData),
  3945.             'mutuelles' => array_values($mutuellesData),
  3946.             'tiers' => array_values($tiersData),
  3947.         ];
  3948.     }
  3949.     /**
  3950.      * @Route("/rdv/{id}/v2", name="editRdvByIDV2", methods={"PUT", "PATCH"})
  3951.      *
  3952.      * Version optimisée de editRdvByID pour les clients
  3953.      * Gestion complète: modification RDV, notifications email/SMS, Google Calendar
  3954.      */
  3955.     public function editRdvByIDV2(
  3956.         int $id,
  3957.         Request $request,
  3958.         PublicFunction $publicFunction,
  3959.         GoogleCalendarService $googleCalendar
  3960.     ): JsonResponse {
  3961.         try {
  3962.             $data json_decode($request->getContent(), true);
  3963.             // Validation du token et récupération du client
  3964.             $validationResult $this->validateTokenAndGetClient($data);
  3965.             if ($validationResult instanceof Response) {
  3966.                 return new JsonResponse(json_decode($validationResult->getContent(), true), $validationResult->getStatusCode());
  3967.             }
  3968.             ['client' => $client] = $validationResult;
  3969.             // Récupération du RDV
  3970.             $rdv $this->entityManager->getRepository(Rdv::class)->find($id);
  3971.             if (!$rdv) {
  3972.                 return new JsonResponse([
  3973.                     'message' => "Aucun rendez-vous trouvé avec cet ID",
  3974.                     'status' => 404
  3975.                 ], 404);
  3976.             }
  3977.             // Vérification des droits (seulement le client peut modifier son RDV)
  3978.             if ($rdv->getIdClient() != $client) {
  3979.                 return new JsonResponse([
  3980.                     'message' => "Vous n'êtes pas autorisé à modifier ce rendez-vous",
  3981.                     'status' => 403
  3982.                 ], 403);
  3983.             }
  3984.             // Sauvegarde des anciennes valeurs pour les notifications
  3985.             $oldDate $rdv->getDate();
  3986.             $oldDuration $rdv->getDuration();
  3987.             // Traitement de la modification
  3988.             $isModified false;
  3989.             $isCancelled false;
  3990.             // Modification de la date
  3991.             if (isset($data['date'])) {
  3992.                 $newDate \DateTime::createFromFormat("d/m/Y H:i"$data['date']);
  3993.                 if (!$newDate) {
  3994.                     return new JsonResponse([
  3995.                         'message' => 'Format de date invalide. Utilisez le format: d/m/Y H:i',
  3996.                         'status' => 400
  3997.                     ], 400);
  3998.                 }
  3999.                 // Vérification de la disponibilité
  4000.                 $audioMotif $this->entityManager->getRepository(AudioMotif::class)
  4001.                     ->findOneBy(['id_audio' => $rdv->getIdAudio(), 'id_motif' => $rdv->getIdMotif()]);
  4002.                 if (!$audioMotif) {
  4003.                     return new JsonResponse([
  4004.                         'message' => "Le motif n'est plus disponible pour cet audioprothésiste",
  4005.                         'status' => 400
  4006.                     ], 400);
  4007.                 }
  4008.                 // Vérification qu'il n'y a pas déjà un RDV à cette nouvelle date
  4009.                 $existingRdv $this->entityManager->getRepository(Rdv::class)
  4010.                     ->findOneBy([
  4011.                         'date' => $newDate,
  4012.                         'id_audio' => $rdv->getIdAudio(),
  4013.                         'id_centre' => $rdv->getIdCentre(),
  4014.                         'id_lieu' => $rdv->getIdLieu(),
  4015.                     ]);
  4016.                 if ($existingRdv && $existingRdv->getId() !== $rdv->getId()) {
  4017.                     return new JsonResponse([
  4018.                         'message' => 'Un rendez-vous existe déjà à ce créneau',
  4019.                         'status' => 409
  4020.                     ], 409);
  4021.                 }
  4022.                 $rdv->setDateOldRdv($oldDate);
  4023.                 $rdv->setDate($newDate);
  4024.                 $isModified true;
  4025.             }
  4026.             // Modification de la durée
  4027.             if (isset($data['duree']) && $data['duree'] !== $oldDuration) {
  4028.                 $rdv->setDuration($data['duree']);
  4029.                 $isModified true;
  4030.             }
  4031.             // Modification de la note
  4032.             if (isset($data['note'])) {
  4033.                 $rdv->setNote($data['note']);
  4034.             }
  4035.             // Gestion de l'annulation (état 2 = annulé)
  4036.             if (isset($data['etat_id']) && $data['etat_id'] == 2) {
  4037.                 $etat $this->entityManager->getRepository(EtatRdv::class)->find(2);
  4038.                 if ($etat) {
  4039.                     $rdv->setIdEtat($etat);
  4040.                     $isCancelled true;
  4041.                     // Suppression des événements Google Calendar
  4042.                     $this->deleteGoogleCalendarEvents($rdv$googleCalendar);
  4043.                 }
  4044.             }
  4045.             // Persistance des modifications
  4046.             $rdv->setGoogleAgendaImported(false);
  4047.             $this->entityManager->flush();
  4048.             // Envoi des notifications
  4049.             if ($isModified && !$isCancelled) {
  4050.                 $this->sendModificationNotifications($rdv$client$oldDate$publicFunction$data);
  4051.                 $this->updateGoogleCalendarEvents($rdv$googleCalendar$data);
  4052.             } elseif ($isCancelled) {
  4053.                 $this->sendCancellationNotifications($rdv$client$publicFunction$data);
  4054.             }
  4055.             // Réponse
  4056.             return new JsonResponse([
  4057.                 'success' => true,
  4058.                 'message' => $isCancelled 'Rendez-vous annulé avec succès' 'Rendez-vous modifié avec succès',
  4059.                 'rdv' => [
  4060.                     'id' => $rdv->getId(),
  4061.                     'date' => $rdv->getDate()->format('Y-m-d H:i:s'),
  4062.                     'duration' => $rdv->getDuration(),
  4063.                     'note' => $rdv->getNote(),
  4064.                     'etat' => [
  4065.                         'id' => $rdv->getIdEtat()->getId(),
  4066.                         'libelle' => $rdv->getIdEtat()->getLibelle(),
  4067.                     ],
  4068.                 ],
  4069.                 'status' => 200
  4070.             ], 200);
  4071.         } catch (\Exception $e) {
  4072.             $this->logger->error("Erreur lors de la modification du RDV #{$id}: " $e->getMessage());
  4073.             return new JsonResponse([
  4074.                 'success' => false,
  4075.                 'message' => 'Une erreur est survenue lors de la modification du rendez-vous.',
  4076.                 'error' => $e->getMessage(),
  4077.                 'status' => 500
  4078.             ], 500);
  4079.         }
  4080.     }
  4081.     /**
  4082.      * Envoie les notifications de modification de RDV
  4083.      */
  4084.     private function sendModificationNotifications(
  4085.         Rdv $rdv,
  4086.         Client $client,
  4087.         \DateTime $oldDate,
  4088.         PublicFunction $publicFunction,
  4089.         array $data
  4090.     ): void {
  4091.         $date $rdv->getDate();
  4092.         $smsDate $date->format('d-m-Y H:i');
  4093.         $formatter = new IntlDateFormatter(
  4094.             'fr_FR',
  4095.             IntlDateFormatter::FULL,
  4096.             IntlDateFormatter::SHORT,
  4097.             null,
  4098.             IntlDateFormatter::GREGORIAN,
  4099.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  4100.         );
  4101.         $smsDateLongFormat $formatter->format($date);
  4102.         $frenchDate ucfirst(preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat));
  4103.         // Notification CLIENT
  4104.         $paramsClient = [
  4105.             'lienModifer' => $_ENV['BASE_client'] . 'mes-rendez-vous',
  4106.             'lienAnnule' => $_ENV['BASE_client'] . 'mes-rendez-vous',
  4107.             'date' => $smsDateLongFormat,
  4108.             'heure' => substr($smsDate1115),
  4109.             'motif' => $rdv->getIdMotif()->getTitre(),
  4110.             'centerName' => $rdv->getIdCentre()->getName(),
  4111.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4112.             'centerPostalCode' => $rdv->getIdCentre()->getPostale(),
  4113.             'audioMail' => $rdv->getIdAudio()->getMail(),
  4114.             'centerPhone' => $rdv->getIdCentre()->getPhone(),
  4115.             'centerCity' => $rdv->getIdCentre()->getCity(),
  4116.             'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  4117.             'titre' => 'Votre rendez-vous est modifié pour le',
  4118.             'frenchDate' => $frenchDate,
  4119.         ];
  4120.         $subject "🔀 Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  4121.         $publicFunction->sendEmail(
  4122.             $paramsClient,
  4123.             $client->getMail(),
  4124.             $client->getName() . ' ' $client->getLastName(),
  4125.             $subject,
  4126.             184
  4127.         );
  4128.         // SMS client si demandé
  4129.         if (isset($data['sms']) && $data['sms']) {
  4130.             $smsMessage "Votre RDV est modifié pour le " substr($smsDate010) . " à " substr($smsDate1115) .
  4131.                           ", en cas d'imprévu contactez votre centre " $rdv->getIdCentre()->getPhone() .
  4132.                           " pour modifier votre consultation.\nNe pas répondre.";
  4133.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$smsMessage$client->getPhone());
  4134.         }
  4135.         // Notification AUDIO
  4136.         $audio $rdv->getIdAudio();
  4137.         if ($audio->getModifRdvMail() || $audio->getModifRdvSms()) {
  4138.             $paramsAudio = [
  4139.                 'lienModifer' => $_ENV['BASE_logiciel'] . 'rdv',
  4140.                 'lienAnnule' => $_ENV['BASE_logiciel'] . 'rdv',
  4141.                 'date' => substr($smsDate010),
  4142.                 'frenchDate' => $frenchDate,
  4143.                 'heure' => substr($smsDate1115),
  4144.                 'motif' => $rdv->getIdMotif()->getTitre(),
  4145.                 'clientPhone' => $client->getPhone(),
  4146.                 'clientNom' => $client->getLastname(),
  4147.                 'clientPrenom' => $client->getName(),
  4148.                 'clientCivilite' => $client->getCivilite(),
  4149.                 'clientPostal' => $client->getPostal(),
  4150.                 'clientMail' => $client->getMail(),
  4151.                 'centerName' => $rdv->getIdCentre()->getName(),
  4152.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4153.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  4154.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4155.                 'idPatient' => $client->getId(),
  4156.                 'proUrl' => $_ENV['BASE_logiciel'],
  4157.                 'audioproName' => $audio->getCivilite() . ' ' $audio->getName() . ' ' $audio->getLastName(),
  4158.                 'titre' => 'Votre rendez-vous est modifié pour le :'
  4159.             ];
  4160.             $mailAudio $audio->getMailNotif() ?? $audio->getMail();
  4161.             if ($audio->getModifRdvMail()) {
  4162.                 $subjectAudio "🔀 Rendez-vous My Audio modifié du " $frenchDate " à " substr($smsDate1115);
  4163.                 $publicFunction->sendEmail($paramsAudio$mailAudio$audio->getName() . ' ' $audio->getLastName(), $subjectAudio186);
  4164.             }
  4165.         }
  4166.     }
  4167.     /**
  4168.      * Envoie les notifications d'annulation de RDV
  4169.      */
  4170.     private function sendCancellationNotifications(
  4171.         Rdv $rdv,
  4172.         Client $client,
  4173.         PublicFunction $publicFunction,
  4174.         array $data
  4175.     ): void {
  4176.         $date $rdv->getDate();
  4177.         $smsDate $date->format('d-m-Y H:i');
  4178.         // Notification CLIENT
  4179.         $paramsClient = [
  4180.             'date' => substr($smsDate010),
  4181.             'lien' => $_ENV['BASE_client'] . 'search',
  4182.             'heure' => substr($smsDate1115),
  4183.             'patientName' => $client->getLastName(),
  4184.             'titre' => 'Votre rendez-vous est annulé :',
  4185.             'centerName' => $rdv->getIdCentre()->getName(),
  4186.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4187.             'centerCity' => $rdv->getIdCentre()->getCity(),
  4188.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4189.             'centerPhone' => $rdv->getIdCentre()->getPhone(),
  4190.             'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  4191.             'audioMail' => $rdv->getIdAudio()->getMail(),
  4192.             'motif' => $rdv->getIdMotif()->getTitre(),
  4193.         ];
  4194.         $subject "❌ Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  4195.         $publicFunction->sendEmail($paramsClient$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject188);
  4196.         // SMS client si demandé
  4197.         if (isset($data['sms']) && $data['sms']) {
  4198.             $smsMessage "Votre RDV a été annulé, contactez votre centre " $rdv->getIdCentre()->getPhone() .
  4199.                           " pour prendre un autre RDV.\nNe pas répondre.";
  4200.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$smsMessage$client->getPhone());
  4201.         }
  4202.         // Notification AUDIO
  4203.         $audio $rdv->getIdAudio();
  4204.         if ($audio->getModifRdvMail()) {
  4205.             $paramsAudio = [
  4206.                 'date' => substr($smsDate010),
  4207.                 'lien' => $_ENV['BASE_client'] . 'search',
  4208.                 'heure' => substr($smsDate1115),
  4209.                 'patientName' => $client->getLastName(),
  4210.                 'titre' => 'Votre rendez-vous est annulé :',
  4211.                 'centerName' => $rdv->getIdCentre()->getName(),
  4212.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4213.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  4214.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4215.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  4216.                 'audioproName' => $audio->getCivilite() . ' ' $audio->getName() . ' ' $audio->getLastName(),
  4217.                 'audioMail' => $audio->getMail(),
  4218.                 'motif' => $rdv->getIdMotif()->getTitre(),
  4219.             ];
  4220.             $mailAudio $audio->getMailNotif() ?? $audio->getMail();
  4221.             $subjectAudio "❌ Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  4222.             $publicFunction->sendEmail($paramsAudio$mailAudio$audio->getName() . ' ' $audio->getLastName(), $subjectAudio188);
  4223.         }
  4224.     }
  4225.     /**
  4226.      * Supprime les événements Google Calendar associés au RDV
  4227.      */
  4228.     private function deleteGoogleCalendarEvents(Rdv $rdvGoogleCalendarService $googleCalendar): void
  4229.     {
  4230.         try {
  4231.             $rdvEvents $this->entityManager->getRepository(RdvEvent::class)
  4232.                 ->findBy(['rdv' => $rdv]);
  4233.             foreach ($rdvEvents as $rdvEvent) {
  4234.                 $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  4235.                 $googleCalendar->deleteEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId());
  4236.                 $this->entityManager->remove($rdvEvent);
  4237.             }
  4238.             $this->entityManager->flush();
  4239.         } catch (\Exception $e) {
  4240.             $this->logger->error("Erreur suppression événements Google Calendar pour RDV #{$rdv->getId()}: " $e->getMessage());
  4241.         }
  4242.     }
  4243.     /**
  4244.      * Met à jour les événements Google Calendar
  4245.      */
  4246.     private function updateGoogleCalendarEvents(Rdv $rdvGoogleCalendarService $googleCalendar, array $data): void
  4247.     {
  4248.         try {
  4249.             $rdvEvents $this->entityManager->getRepository(RdvEvent::class)
  4250.                 ->findBy(['rdv' => $rdv]);
  4251.             $data['rdv'] = $rdv->getId();
  4252.             if ($rdv->getIdClient() !== null) {
  4253.                 $data['client_id'] = $rdv->getIdClient()->getId();
  4254.             }
  4255.             foreach ($rdvEvents as $rdvEvent) {
  4256.                 $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  4257.                 $googleCalendar->updateEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
  4258.             }
  4259.         } catch (\Exception $e) {
  4260.             $this->logger->error("Erreur mise à jour événements Google Calendar pour RDV #{$rdv->getId()}: " $e->getMessage());
  4261.         }
  4262.     }
  4263.     /**
  4264.      * @Route("/rdv/{id}/trusteduser", name="contactTrustedUser", methods={"POST"})
  4265.      */
  4266.     public function contactTrustedUser(Request $requestPublicFunction $publicFunction)
  4267.     {
  4268.         $pastDate $rdv->getDate();
  4269.         $data json_decode($request->getContent(), true);
  4270.         $entityManager $this->getDoctrine()->getManager();
  4271.         if (!isset($data["token"])) {
  4272.             return new Response(json_encode([
  4273.                 "message" => "Pas de token n'a été spécifié",
  4274.                 "status" => 401,
  4275.             ]), 401);
  4276.         }
  4277.         /** @var Token */
  4278.         $token $this->getDoctrine()
  4279.             ->getRepository(Token::class)
  4280.             ->findOneBy(['token' => $data["token"]]);
  4281.         if (!$token) {
  4282.             return new Response(json_encode([
  4283.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  4284.                 "status" => 404,
  4285.             ]), 404);
  4286.         }
  4287.         // get token age
  4288.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  4289.         // if the token if older than 7 days
  4290.         if ($dateDiff->7) {
  4291.             $entityManager->remove($token);
  4292.             $entityManager->flush();
  4293.             return $this->json([
  4294.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  4295.                 'path' => 'src/Controller/ClientController.php',
  4296.                 "status" => 401,
  4297.             ], 401);
  4298.         }
  4299.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  4300.             return new Response(json_encode([
  4301.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  4302.                 "status" => 404,
  4303.             ]), 404);
  4304.         }
  4305.         if (isset($data["date"])) {
  4306.             // remove the taken schedule by rdv to make sure there is no overlap
  4307.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4308.             $audioMotif $this->getDoctrine()
  4309.                 ->getRepository(AudioMotif::class)
  4310.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  4311.             if ($audioMotif == null) {
  4312.                 return new Response(json_encode(([
  4313.                     'message' => 'Error, no motif of this id found at this audio',
  4314.                     'path' => 'src/Controller/RdvController.php',
  4315.                     "status" => 400,
  4316.                 ])), 400);
  4317.             }
  4318.             if ($rdv->getIdAudio()->getIsIndie()) {
  4319.                 if ($rdv->getIdCentre()) {
  4320.                     // regular centre audio indie
  4321.                     /** @var AudioCentre */
  4322.                     $liaison $this->getDoctrine()
  4323.                         ->getRepository(AudioCentre::class)
  4324.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  4325.                     if ($liaison == null) {
  4326.                         return new Response(json_encode(([
  4327.                             'message' => 'Error, audio isnt part of the centre',
  4328.                             'path' => 'src/Controller/RdvController.php',
  4329.                             "status" => 400,
  4330.                         ])), 400);
  4331.                     }
  4332.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  4333.                         return new Response(json_encode(([
  4334.                             'message' => 'Error, no horaire found for this audio',
  4335.                             'path' => 'src/Controller/RdvController.php',
  4336.                             "status" => 400,
  4337.                         ])), 400);
  4338.                     }
  4339.                     // if ($publicFunction->calculScheduleFitDate($liaison->getHoraire(), $rdv->getIdAudio(), $date, $audioMotif->getDuration(), $rdv->getIdCentre()) == false) {
  4340.                     //     return new Response(json_encode(([
  4341.                     //         'message' => 'Error, no timestamp found at this time',
  4342.                     //         'path' => 'src/Controller/RdvController.php',
  4343.                     //         "status" => 400,
  4344.                     //     ])),400);
  4345.                     // }
  4346.                 } else {
  4347.                     // lieu audio indie
  4348.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  4349.                         return new Response(json_encode(([
  4350.                             'message' => 'Error, no horaire found for this audio',
  4351.                             'path' => 'src/Controller/RdvController.php',
  4352.                             "status" => 400,
  4353.                         ])), 400);
  4354.                     }
  4355.                     // if ($publicFunction->calculScheduleFitDate($rdv->getIdLieu()->getHoraire(), $rdv->getIdAudio(), $date, $audioMotif->getDuration(), null, $rdv->getIdLieu()) == false) {
  4356.                     //     return new Response(json_encode(([
  4357.                     //         'message' => 'Error, no timestamp found at this time',
  4358.                     //         'path' => 'src/Controller/RdvController.php',
  4359.                     //         "status" => 400,
  4360.                     //     ])),400);
  4361.                     // }
  4362.                 }
  4363.             } else {
  4364.                 // regular centre
  4365.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  4366.                     return new Response(json_encode(([
  4367.                         'message' => 'Error, no horaire found for this audio',
  4368.                         'path' => 'src/Controller/RdvController.php',
  4369.                         "status" => 400,
  4370.                     ])), 400);
  4371.                 }
  4372.                 // if ($publicFunction->calculScheduleFitDate($rdv->getIdCentre()->getHoraire(), $rdv->getIdAudio(), $date, $audioMotif->getDuration(), $rdv->getIdCentre()) == false) {
  4373.                 //     return new Response(json_encode(([
  4374.                 //         'message' => 'Error, no timestamp found at this time',
  4375.                 //         'path' => 'src/Controller/RdvController.php',
  4376.                 //         "status" => 400,
  4377.                 //     ])),400);
  4378.                 // }
  4379.             }
  4380.             $rdv->setDate($date);
  4381.         }
  4382.         $date $rdv->getDate();
  4383.         $smsDate $date->format('d-m-Y H:i');
  4384.         $oldDate $pastDate->format('d-m-Y H:i');
  4385.         $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>");
  4386.         return new Response(json_encode(([
  4387.             "id" => $rdv->getId(),
  4388.             "status" => 200,
  4389.         ])));
  4390.     }
  4391.     /**
  4392.      * @Route("/rdv/{id}", name="editRdvByID", methods={"PUT"})
  4393.      */
  4394.     public function editRdvByID(PublicFunction $publicFunctionRdv $rdvRequest $requestGoogleCalendarService $googleCalendarRdvSmsService $rdvSms): Response
  4395.     {
  4396.         $pastDate $rdv->getDate();
  4397.         $pastDuration $rdv->getDuration();
  4398.         $data json_decode($request->getContent(), true);
  4399.         $entityManager $this->getDoctrine()->getManager();
  4400.         if (!isset($data["token"])) {
  4401.             return new Response(json_encode([
  4402.                 "message" => "Pas de token n'a été spécifié",
  4403.                 "status" => 401,
  4404.             ]), 401);
  4405.         }
  4406.         /** @var Token */
  4407.         $token $this->getDoctrine()
  4408.             ->getRepository(Token::class)
  4409.             ->findOneBy(['token' => $data["token"]]);
  4410.         if (!$token) {
  4411.             return new Response(json_encode([
  4412.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  4413.                 "status" => 404,
  4414.             ]), 404);
  4415.         }
  4416.         // get token age
  4417.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  4418.         // if the token if older than 7 days
  4419.         if ($dateDiff->7) {
  4420.             $entityManager->remove($token);
  4421.             $entityManager->flush();
  4422.             return $this->json([
  4423.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  4424.                 'path' => 'src/Controller/ClientController.php',
  4425.                 "status" => 401,
  4426.             ], 401);
  4427.         }
  4428.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  4429.             return new Response(json_encode([
  4430.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  4431.                 "status" => 404,
  4432.             ]), 404);
  4433.         }
  4434.         if (isset($data["etat_id"])) {
  4435.             $etat $this->getDoctrine()
  4436.                 ->getRepository(EtatRdv::class)
  4437.                 ->findOneBy(['id' => $data["etat_id"]]);
  4438.             if ($etat == null) {
  4439.                 return new Response(json_encode(([
  4440.                     'message' => 'Error, no etat found at this id',
  4441.                     'path' => 'src/Controller/TrustedUserController.php',
  4442.                     "status" => 400,
  4443.                 ])), 400);
  4444.             }
  4445.             $rdv->setIdEtat($etat);
  4446.         }
  4447.         if (isset($data["audio_id"])) {
  4448.             $audio $this->getDoctrine()
  4449.                 ->getRepository(Audio::class)
  4450.                 ->findOneBy(['id' => $data["audio_id"]]);
  4451.             if ($audio == null) {
  4452.                 return new Response(json_encode(([
  4453.                     'message' => 'Error, no audio found at this id',
  4454.                     'path' => 'src/Controller/TrustedUserController.php',
  4455.                     "status" => 400,
  4456.                 ])), 400);
  4457.             }
  4458.             $rdv->setIdAudio($audio);
  4459.         }
  4460.         if (isset($data["motif_id"])) {
  4461.             $motif $this->getDoctrine()
  4462.                 ->getRepository(Motif::class)
  4463.                 ->find($data["motif_id"]);
  4464.             if ($motif == null) {
  4465.                 return new Response(json_encode(([
  4466.                     'message' => 'Error, no motif found at this id',
  4467.                     'path' => 'src/Controller/TrustedUserController.php',
  4468.                     "status" => 400,
  4469.                 ])), 400);
  4470.             }
  4471.             $rdv->setIdMotif($motif);
  4472.         }
  4473.         if (isset($data["client_id"])) {
  4474.             $client $this->getDoctrine()
  4475.                 ->getRepository(Client::class)
  4476.                 ->findOneBy(['id' => $data["client_id"]]);
  4477.             if ($client == null) {
  4478.                 return new Response(json_encode(([
  4479.                     'message' => 'Error, no client found at this id',
  4480.                     'path' => 'src/Controller/TrustedUserController.php',
  4481.                     "status" => 400,
  4482.                 ])), 400);
  4483.             }
  4484.             $rdv->setIdClient($client);
  4485.         }
  4486.         // set client status
  4487.         if (isset($data["client_status_id"])) {
  4488.             $status $this->getDoctrine()
  4489.                 ->getRepository(ClientStatus::class)
  4490.                 ->findOneBy(['id' => $data["client_status_id"]]);
  4491.             if ($status == null) {
  4492.                 return new Response(json_encode(([
  4493.                     'message' => 'Error, no status found at this id',
  4494.                     'path' => 'src/Controller/TrustedUserController.php',
  4495.                     "status" => 400,
  4496.                 ])), 400);
  4497.             }
  4498.             $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  4499.             $client->setClientStatus($status);
  4500.             $client->setLastUpdateStatus(new \DateTimeImmutable);
  4501.         }
  4502.         if (isset($data["date"])) {
  4503.             $submittedDate $data['date'] ?? null;
  4504.             $newDate \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4505.             $currentDate $rdv->getDate();
  4506.             if (!$currentDate || $currentDate->format('d/m/Y H:i') !== $newDate->format('d/m/Y H:i')) {
  4507.                 $rdv->setDateOldRdv($currentDate);
  4508.             }
  4509.             // remove the taken schedule by rdv to make sure there is no overlap
  4510.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4511.             $dateInput \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4512.             $audioMotif $this->getDoctrine()
  4513.                 ->getRepository(AudioMotif::class)
  4514.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  4515.             if ($audioMotif == null) {
  4516.                 return new Response(json_encode(([
  4517.                     'message' => 'Error, no motif of this id found at this audio',
  4518.                     'path' => 'src/Controller/RdvController.php',
  4519.                     "status" => 400,
  4520.                 ])), 400);
  4521.             }
  4522.             if ($rdv->getIdAudio()->getIsIndie()) {
  4523.                 if ($rdv->getIdCentre()) {
  4524.                     // regular centre audio indie
  4525.                     /** @var AudioCentre */
  4526.                     $liaison $this->getDoctrine()
  4527.                         ->getRepository(AudioCentre::class)
  4528.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  4529.                     if ($liaison == null) {
  4530.                         return new Response(json_encode(([
  4531.                             'message' => 'Error, audio isnt part of the centre',
  4532.                             'path' => 'src/Controller/RdvController.php',
  4533.                             "status" => 400,
  4534.                         ])), 400);
  4535.                     }
  4536.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  4537.                         return new Response(json_encode(([
  4538.                             'message' => 'Error, no horaire found for this audio',
  4539.                             'path' => 'src/Controller/RdvController.php',
  4540.                             "status" => 400,
  4541.                         ])), 400);
  4542.                     }
  4543.                 } else {
  4544.                     // lieu audio indie
  4545.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  4546.                         return new Response(json_encode(([
  4547.                             'message' => 'Error, no horaire found for this audio',
  4548.                             'path' => 'src/Controller/RdvController.php',
  4549.                             "status" => 400,
  4550.                         ])), 400);
  4551.                     }
  4552.                 }
  4553.             } else {
  4554.                 // regular centre
  4555.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  4556.                     return new Response(json_encode(([
  4557.                         'message' => 'Error, no horaire found for this audio',
  4558.                         'path' => 'src/Controller/RdvController.php',
  4559.                         "status" => 400,
  4560.                     ])), 400);
  4561.                 }
  4562.             }
  4563.             $rdv->setDate($date);
  4564.         }
  4565.         if (isset($data["comment"]) && $token->getIdClient()) {
  4566.             $rdv->setComment($data["comment"]);
  4567.         }
  4568.         if (isset($data["review"]) && $token->getIdClient()) {
  4569.             $rdv->setReview($data["review"]);
  4570.         }
  4571.         if (isset($data["note"])) {
  4572.             $rdv->setNote($data["note"]);
  4573.         }
  4574.         if (isset($data["duree"])) {
  4575.             $rdv->setDuration($data["duree"]);
  4576.         }
  4577.         ////// SMSEMAIL A décommenter pour activer l'envoi de SMS + MAIL pour modification annulation de RDV, coté audio / client SMSEMAIL ////
  4578.         $date $rdv->getDate();
  4579.         $smsDate $date->format('d-m-Y H:i');
  4580.         $oldDate $pastDate->format('d-m-Y H:i');
  4581.         $locale 'fr_FR';
  4582.         $formatter = new IntlDateFormatter(
  4583.             $locale,
  4584.             IntlDateFormatter::FULL,
  4585.             IntlDateFormatter::SHORT,
  4586.             null,
  4587.             IntlDateFormatter::GREGORIAN,
  4588.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  4589.         );
  4590.         $smsDateLongFormat $formatter->format($date);
  4591.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  4592.         $frenchDate ucfirst($frenchDate);
  4593.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  4594.         // notif client
  4595.         if ($rdv->getIdEtat()->getId() != 2) {
  4596.             if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  4597.                 if ($data["sms"]) {
  4598.                     $params = array(
  4599.                         "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  4600.                         "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  4601.                         "date" => $smsDateLongFormat,
  4602.                         "heure" => substr($smsDate1115),
  4603.                         "motif" => $rdv->getIdMotif()->getTitre(),
  4604.                         "centerName" => $rdv->getIdCentre()->getName(),
  4605.                         "centerAddress" => $rdv->getIdCentre()->getAddress(),
  4606.                         "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  4607.                         "audioMail" => $rdv->getIdAudio()->getMail(),
  4608.                         "centerPhone" => $rdv->getIdCentre()->getPhone(),
  4609.                         "centerCity" => $rdv->getIdCentre()->getCity(),
  4610.                         "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  4611.                         'titre' => 'Votre rendez-vous est modifié pour le',
  4612.                         'frenchDate' => $frenchDate,
  4613.                     );
  4614.                     $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  4615.                     $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject184);
  4616.                     $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.";
  4617.                     $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  4618.                 }
  4619.             }
  4620.         }
  4621.         //     //// == suppression
  4622.         else if ($rdv->getIdEtat()->getId() == 2) {
  4623.             // delete google agenda event
  4624.             $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  4625.                 ->findBy(array('rdv' => $rdv));
  4626.             foreach ($rdvEvents as $rdvEvent) {
  4627.                 $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  4628.                 if ($googleCalendar) {
  4629.                     $googleCalendar->deleteEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId());
  4630.                     $entityManager->remove($rdvEvent);
  4631.                     $entityManager->flush();
  4632.                 }
  4633.             }
  4634.             //if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  4635.             //if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {                   
  4636.             $params = array(
  4637.                 "date" => substr($smsDate010),
  4638.                 "lien" => "{$_ENV['BASE_client']}search",
  4639.                 "heure" => substr($smsDate1115),
  4640.                 "patientName" => $client->getLastName(),
  4641.                 'titre' => 'Votre rendez-vous est annulé :',
  4642.                 'centerName' => $rdv->getIdCentre()->getName(),
  4643.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4644.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  4645.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4646.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  4647.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  4648.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  4649.                 'motif' => $rdv->getIdMotif()->getTitre(),
  4650.             );
  4651.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  4652.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject188);
  4653.             if ($data["sms"]) {
  4654.                 $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  4655.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  4656.             }
  4657.             //}
  4658.         }
  4659.         // set center
  4660.         if (isset($data["centre_id"])) {
  4661.             $entityManager $this->getDoctrine()->getManager();
  4662.             $centreId $data["centre_id"];
  4663.             $centre $entityManager->getRepository(Centre::class)->find($centreId);
  4664.             if (!$centre) {
  4665.                 return $this->json([
  4666.                     'message' => 'Error, no Centre found with this ID',
  4667.                     'path' => 'src/Controller/YourController.php',
  4668.                 ]);
  4669.             }
  4670.             $rdv->setIdCentre($centre);
  4671.         }
  4672.         $rdv->setGoogleAgendaImported(false);
  4673.         //notif Audio
  4674.         if ($rdv->getIdEtat()->getId() != 2) {
  4675.             if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  4676.                 if ($data["sms"]) {
  4677.                     $params = array(
  4678.                         "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  4679.                         "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  4680.                         "date" => substr($smsDate010),
  4681.                         "frenchDate" => $frenchDate,
  4682.                         "heure" => substr($smsDate1115),
  4683.                         'motif' => $rdv->getIdMotif()->getTitre(),
  4684.                         'clientPhone' => $client->getPhone(),
  4685.                         'clientNom' => $client->getLastname(),
  4686.                         'clientPrenom' => $client->getName(),
  4687.                         'clientCivilite' => $client->getCivilite(),
  4688.                         'clientPostal' => $client->getPostal(),
  4689.                         'clientMail' => $client->getMail(),
  4690.                         'centerName' => $rdv->getIdCentre()->getName(),
  4691.                         'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4692.                         'centerCity' => $rdv->getIdCentre()->getCity(),
  4693.                         'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4694.                         'idPatient' => $client->getId(),
  4695.                         'proUrl' => "{$_ENV['BASE_logiciel']}",
  4696.                         'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  4697.                         'titre' => 'Votre rendez-vous est modifié pour le :'
  4698.                     );
  4699.                     $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  4700.                     $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  4701.                     if ($rdv->getIdAudio()->getModifRdvMail()) {
  4702.                         $subject "🔀 Rendez-vous My Audio modifié du " $frenchDate " à " substr($smsDate1115);
  4703.                         $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject186);
  4704.                     }
  4705.                     if ($rdv->getIdAudio()->getModifRdvSms()) {
  4706.                         // we ignore the sms send to the audio for the case he modify the rdv (so lets commented)
  4707.                         $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.";
  4708.                         //$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $phoneAudio);
  4709.                     }
  4710.                 }
  4711.             }
  4712.         } else if ($rdv->getIdEtat()->getId() == 2) {
  4713.             if ($data["sms"]) {
  4714.                 $params = array(
  4715.                     "date" => substr($smsDate010),
  4716.                     "lien" => "{$_ENV['BASE_client']}search",
  4717.                     "heure" => substr($smsDate1115),
  4718.                     "patientName" => $client->getLastName(),
  4719.                     'titre' => 'Votre rendez-vous est annulé :',
  4720.                     'centerName' => $rdv->getIdCentre()->getName(),
  4721.                     'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4722.                     'centerCity' => $rdv->getIdCentre()->getCity(),
  4723.                     'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4724.                     'centerPhone' => $rdv->getIdCentre()->getPhone(),
  4725.                     'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  4726.                     'audioMail' => $rdv->getIdAudio()->getMail(),
  4727.                     'motif' => $rdv->getIdMotif()->getTitre(),
  4728.                 );
  4729.                 $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  4730.                 $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  4731.                 if ($rdv->getIdAudio()->getModifRdvMail()) {
  4732.                     $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  4733.                     $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject188);
  4734.                 }
  4735.                 if ($rdv->getIdAudio()->getModifRdvSms()) {
  4736.                     $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.";
  4737.                     // $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $phoneAudio);
  4738.                 }
  4739.             }
  4740.         }
  4741.         $entityManager->flush();
  4742.         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"]))) {
  4743.             if (is_null($rdv->getIdClientTemp())) {
  4744.                 $clientRDV $this->getDoctrine()
  4745.                     ->getRepository(Client::class)
  4746.                     ->findOneBy(['id' => $rdv->getIdClient()->getId()]);
  4747.                 $clientRDV->setName($data["prenom_patient"]);
  4748.                 $clientRDV->setLastname($data["nom_patient"]);
  4749.                 $clientRDV->setMail($data["mail_patient"]);
  4750.                 $clientRDV->setPhone($data["portable_patient"]);
  4751.                 $clientRDV->setPhoneFixe($data["fixe_patient"]);
  4752.             } else {
  4753.                 $clientRDV $this->getDoctrine()
  4754.                     ->getRepository(ClientTemp::class)
  4755.                     ->findOneBy(['id' => $rdv->getIdClientTemp()->getId()]);
  4756.                 $clientRDV->setName($data["prenom_patient"]);
  4757.                 $clientRDV->setLastname($data["nom_patient"]);
  4758.                 $clientRDV->setMail($data["mail_patient"]);
  4759.                 $clientRDV->setPhone($data["portable_patient"]);
  4760.                 $clientRDV->setPhoneFixe($data["fixe_patient"]);
  4761.             }
  4762.             if (!empty($data["birthday_patient"])) {
  4763.                 $birth \DateTime::createFromFormat("Y-m-d"$data["birthday_patient"]);
  4764.                 $clientRDV->setBirthdate($birth);
  4765.             }
  4766.             $entityManager->flush();
  4767.         }
  4768.         if (is_null($rdv->getIdClient())) {
  4769.             $prenom_patient $rdv->getIdClientTemp()->getName();
  4770.             $nom_patient $rdv->getIdClientTemp()->getLastname();
  4771.             $mail_patient $rdv->getIdClientTemp()->getMail();
  4772.             $portable_patient $rdv->getIdClientTemp()->getPhone();
  4773.             $fixe_patient $rdv->getIdClientTemp()->getPhoneFixe();
  4774.             $birthday $rdv->getIdClientTemp()->getBirthdate();
  4775.         } elseif (is_null($rdv->getIdClientTemp())) {
  4776.             $prenom_patient =  $rdv->getIdClient()->getName();
  4777.             $nom_patient $rdv->getIdClient()->getLastname();
  4778.             $mail_patient $rdv->getIdClient()->getMail();
  4779.             $portable_patient $rdv->getIdClient()->getPhone();
  4780.             $fixe_patient $rdv->getIdClient()->getPhoneFixe();
  4781.             $birthday $rdv->getIdClient()->getBirthdate();
  4782.         } else {
  4783.             $prenom_patient "";
  4784.             $nom_patient "";
  4785.             $mail_patient "";
  4786.             $portable_patient "";
  4787.             $fixe_patient "";
  4788.             $birthday "";
  4789.         }
  4790.         /* generate sms notif on update */
  4791.         // update sms notification     
  4792.         $rdvSms->updateRdvSms($rdv);
  4793.         // google calendar update
  4794.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  4795.             ->findBy(array('audio' => $rdv->getIdAudio()));
  4796.         $data['rdv'] = $rdv->getId();
  4797.         if ($rdv->getIdClient() !== null) {
  4798.             $data["client_id"] = $rdv->getIdClient()->getId();
  4799.         }
  4800.         if ($rdv->getIdClientTemp() !== null) {
  4801.             $data["client_id_temp"] = $rdv->getIdClientTemp()->getId();
  4802.         }
  4803.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  4804.             ->findBy(array('rdv' => $rdv));
  4805.         foreach ($rdvEvents as $rdvEvent) {
  4806.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  4807.             $googleCalendar->updateEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
  4808.         }
  4809.         $synchronisationCosium $this->getDoctrine()->getRepository(SynchronisationCosium::class)->findOneBy(["audio" => $rdv->getIdAudio()->getId()]);
  4810.         $cosiumCenter $this->getDoctrine()->getRepository(CosiumCenter::class)->findOneBy(["synchronisationCosium" => $synchronisationCosium"center" => $rdv->getIdCentre()]);
  4811.         if ($cosiumCenter) {
  4812.             $this->clientCosiumService->deleteRdv($synchronisationCosium$rdv);
  4813.             $this->clientCosiumService->createAgenda($synchronisationCosium$rdv$cosiumCenter);
  4814.         }
  4815.         $token $this->entityManager
  4816.              ->getRepository(Token::class)
  4817.              ->findOneBy(['token' => $data['token']]);
  4818.         $tokenAudioId $token->getIdAudio()->getId();
  4819.         $requestAudioId $data['audio_id'] ?? null;
  4820.         if ($requestAudioId && $requestAudioId == $tokenAudioId) {
  4821.         // After successfully updating the RDV
  4822.         $this->mercure->publishRdvUpdate($rdv'updated');
  4823.         }
  4824.         return new Response(json_encode(([
  4825.             "id" => $rdv->getId(),
  4826.             "motif_id" => $rdv->getIdMotif()->getId(),
  4827.             "motif_libelle" => $rdv->getIdMotif()->getTitre(),
  4828.             "audio_id" => $rdv->getIdAudio()->getId(),
  4829.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  4830.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  4831.             "fullName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  4832.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  4833.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  4834.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  4835.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  4836.             "centre_name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : null,
  4837.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  4838.             "etat_id" => $rdv->getIdEtat()->getId(),
  4839.             "date" => $rdv->getDate(),
  4840.             "comment" => $rdv->getComment(),
  4841.             "note" => $rdv->getNote(),
  4842.             "review" => $rdv->getReview(),
  4843.             "clientEtatId" => $client->getClientStatus() ? $client->getClientStatus()->getId() : 0,
  4844.             "prenom_patient" => $prenom_patient,
  4845.             "nom_patient" => $nom_patient,
  4846.             "mail_patient" => $mail_patient,
  4847.             "portable_patient" => $portable_patient,
  4848.             "fixe_patient" => $fixe_patient,
  4849.             "birthday" => $birthday,
  4850.             "status" => 200,
  4851.         ])));
  4852.     }
  4853.     /**
  4854.      * @Route("/rdv-by-patient/{id}", name="editRdvByIDFromPatient", methods={"PUT"})
  4855.      */
  4856.     public function editRdvByIDFromPatient(PublicFunction $publicFunctionRdv $rdvRequest $request): Response
  4857.     {
  4858.         $pastDate $rdv->getDate();
  4859.         $pastDuration $rdv->getDuration();
  4860.         $data json_decode($request->getContent(), true);
  4861.         $entityManager $this->getDoctrine()->getManager();
  4862.         if (!isset($data["token"])) {
  4863.             return new Response(json_encode([
  4864.                 "message" => "Pas de token n'a été spécifié",
  4865.                 "status" => 401,
  4866.             ]), 401);
  4867.         }
  4868.         /** @var Token */
  4869.         $token $this->getDoctrine()
  4870.             ->getRepository(Token::class)
  4871.             ->findOneBy(['token' => $data["token"]]);
  4872.         if (!$token) {
  4873.             return new Response(json_encode([
  4874.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  4875.                 "status" => 404,
  4876.             ]), 404);
  4877.         }
  4878.         // get token age
  4879.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  4880.         // if the token if older than 7 days
  4881.         if ($dateDiff->7) {
  4882.             $entityManager->remove($token);
  4883.             $entityManager->flush();
  4884.             return $this->json([
  4885.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  4886.                 'path' => 'src/Controller/ClientController.php',
  4887.                 "status" => 401,
  4888.             ], 401);
  4889.         }
  4890.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  4891.             return new Response(json_encode([
  4892.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  4893.                 "status" => 404,
  4894.             ]), 404);
  4895.         }
  4896.         if (isset($data["etat_id"])) {
  4897.             $etat $this->getDoctrine()
  4898.                 ->getRepository(EtatRdv::class)
  4899.                 ->findOneBy(['id' => $data["etat_id"]]);
  4900.             if ($etat == null) {
  4901.                 return new Response(json_encode(([
  4902.                     'message' => 'Error, no etat found at this id',
  4903.                     'path' => 'src/Controller/TrustedUserController.php',
  4904.                     "status" => 400,
  4905.                 ])), 400);
  4906.             }
  4907.             $rdv->setIdEtat($etat);
  4908.         }
  4909.         if (isset($data["audio_id"])) {
  4910.             $audio $this->getDoctrine()
  4911.                 ->getRepository(Audio::class)
  4912.                 ->findOneBy(['id' => $data["audio_id"]]);
  4913.             if ($audio == null) {
  4914.                 return new Response(json_encode(([
  4915.                     'message' => 'Error, no audio found at this id',
  4916.                     'path' => 'src/Controller/TrustedUserController.php',
  4917.                     "status" => 400,
  4918.                 ])), 400);
  4919.             }
  4920.             $rdv->setIdAudio($audio);
  4921.         }
  4922.         if (isset($data["motif_id"])) {
  4923.             $motif $this->getDoctrine()
  4924.                 ->getRepository(Motif::class)
  4925.                 ->find($data["motif_id"]);
  4926.             if ($motif == null) {
  4927.                 return new Response(json_encode(([
  4928.                     'message' => 'Error, no motif found at this id',
  4929.                     'path' => 'src/Controller/TrustedUserController.php',
  4930.                     "status" => 400,
  4931.                 ])), 400);
  4932.             }
  4933.             $rdv->setIdMotif($motif);
  4934.         }
  4935.         if (isset($data["client_id"])) {
  4936.             $client $this->getDoctrine()
  4937.                 ->getRepository(Client::class)
  4938.                 ->findOneBy(['id' => $data["client_id"]]);
  4939.             if ($client == null) {
  4940.                 return new Response(json_encode(([
  4941.                     'message' => 'Error, no client found at this id',
  4942.                     'path' => 'src/Controller/TrustedUserController.php',
  4943.                     "status" => 400,
  4944.                 ])), 400);
  4945.             }
  4946.             $rdv->setIdClient($client);
  4947.         }
  4948.         if (isset($data["date"])) {
  4949.             // remove the taken schedule by rdv to make sure there is no overlap
  4950.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4951.             $dateInput \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4952.             $audioMotif $this->getDoctrine()
  4953.                 ->getRepository(AudioMotif::class)
  4954.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  4955.             if ($audioMotif == null) {
  4956.                 return new Response(json_encode(([
  4957.                     'message' => 'Error, no motif of this id found at this audio',
  4958.                     'path' => 'src/Controller/RdvController.php',
  4959.                     "status" => 400,
  4960.                 ])), 400);
  4961.             }
  4962.             if ($rdv->getIdAudio()->getIsIndie()) {
  4963.                 if ($rdv->getIdCentre()) {
  4964.                     // regular centre audio indie
  4965.                     /** @var AudioCentre */
  4966.                     $liaison $this->getDoctrine()
  4967.                         ->getRepository(AudioCentre::class)
  4968.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  4969.                     if ($liaison == null) {
  4970.                         return new Response(json_encode(([
  4971.                             'message' => 'Error, audio isnt part of the centre',
  4972.                             'path' => 'src/Controller/RdvController.php',
  4973.                             "status" => 400,
  4974.                         ])), 400);
  4975.                     }
  4976.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  4977.                         return new Response(json_encode(([
  4978.                             'message' => 'Error, no horaire found for this audio',
  4979.                             'path' => 'src/Controller/RdvController.php',
  4980.                             "status" => 400,
  4981.                         ])), 400);
  4982.                     }
  4983.                 } else {
  4984.                     // lieu audio indie
  4985.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  4986.                         return new Response(json_encode(([
  4987.                             'message' => 'Error, no horaire found for this audio',
  4988.                             'path' => 'src/Controller/RdvController.php',
  4989.                             "status" => 400,
  4990.                         ])), 400);
  4991.                     }
  4992.                 }
  4993.             } else {
  4994.                 // regular centre
  4995.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  4996.                     return new Response(json_encode(([
  4997.                         'message' => 'Error, no horaire found for this audio',
  4998.                         'path' => 'src/Controller/RdvController.php',
  4999.                         "status" => 400,
  5000.                     ])), 400);
  5001.                 }
  5002.             }
  5003.             $rdv->setDate($date);
  5004.         }
  5005.         if (isset($data["comment"]) && $token->getIdClient()) {
  5006.             $rdv->setComment($data["comment"]);
  5007.         }
  5008.         if (isset($data["review"]) && $token->getIdClient()) {
  5009.             $rdv->setReview($data["review"]);
  5010.         }
  5011.         if (isset($data["note"])) {
  5012.             $rdv->setNote($data["note"]);
  5013.         }
  5014.         if (isset($data["duree"])) {
  5015.             $rdv->setDuration($data["duree"]);
  5016.         }
  5017.         ////// SMSEMAIL A décommenter pour activer l'envoi de SMS + MAIL pour modification annulation de RDV, coté audio / client SMSEMAIL ////
  5018.         $date $rdv->getDate();
  5019.         $smsDate $date->format('d-m-Y H:i');
  5020.         $oldDate $pastDate->format('d-m-Y H:i');
  5021.         $locale 'fr_FR';
  5022.         $formatter = new IntlDateFormatter(
  5023.             $locale,
  5024.             IntlDateFormatter::FULL,
  5025.             IntlDateFormatter::SHORT,
  5026.             null,
  5027.             IntlDateFormatter::GREGORIAN,
  5028.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  5029.         );
  5030.         $smsDateLongFormat $formatter->format($date);
  5031.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  5032.         $frenchDate ucfirst($frenchDate);
  5033.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  5034.         // notif client
  5035.         if ($rdv->getIdEtat()->getId() != 2) {
  5036.             if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  5037.                 $params = array(
  5038.                     "lienModifier" => "{$_ENV['BASE_client']}mes-rendez-vous",
  5039.                     "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  5040.                     "date" => $smsDateLongFormat,
  5041.                     "heure" => substr($smsDate1115),
  5042.                     "motif" => $rdv->getIdMotif()->getTitre(),
  5043.                     "centerName" => $rdv->getIdCentre()->getName(),
  5044.                     "centerAddress" => $rdv->getIdCentre()->getAddress(),
  5045.                     "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  5046.                     "audioMail" => $rdv->getIdAudio()->getMail(),
  5047.                     "centerPhone" => $rdv->getIdCentre()->getPhone(),
  5048.                     "centerCity" => $rdv->getIdCentre()->getCity(),
  5049.                     "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  5050.                     'titre' => 'Votre rendez-vous est modifié pour le',
  5051.                     'frenchDate' => $frenchDate,
  5052.                 );
  5053.                 $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  5054.                 $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject184);
  5055.                 $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.";
  5056.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  5057.             }
  5058.         }
  5059.         //     //// == suppression
  5060.         else if ($rdv->getIdEtat()->getId() == 2) {
  5061.             //if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  5062.             //if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {                   
  5063.             $params = array(
  5064.                 "date" => substr($smsDate010),
  5065.                 "lien" => "{$_ENV['BASE_client']}audioprothesiste/{$rdv->getIdCentre()->getCity()}/{$rdv->getIdCentre()->getPostale()}/{$rdv->getIdCentre()->getName()}/prise-de-rdv-audioprothesiste-rapide/{$rdv->getIdCentre()->getId()}",
  5066.                 "heure" => substr($smsDate1115),
  5067.                 "patientName" => $client->getLastName(),
  5068.                 'titre' => 'Votre rendez-vous est annulé :',
  5069.                 'centerName' => $rdv->getIdCentre()->getName(),
  5070.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  5071.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  5072.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  5073.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  5074.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  5075.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  5076.                 'motif' => $rdv->getIdMotif()->getTitre(),
  5077.             );
  5078.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  5079.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject203);
  5080.             $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  5081.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  5082.             //}
  5083.         }
  5084.         // set center
  5085.         if (isset($data["centre_id"])) {
  5086.             $entityManager $this->getDoctrine()->getManager();
  5087.             $centreId $data["centre_id"];
  5088.             $centre $entityManager->getRepository(Centre::class)->find($centreId);
  5089.             if (!$centre) {
  5090.                 return $this->json([
  5091.                     'message' => 'Error, no Centre found with this ID',
  5092.                     'path' => 'src/Controller/YourController.php',
  5093.                 ]);
  5094.             }
  5095.             $rdv->setIdCentre($centre);
  5096.         }
  5097.         $rdv->setGoogleAgendaImported(false);
  5098.         //notif Audio
  5099.         if ($rdv->getIdEtat()->getId() != 2) {
  5100.             if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  5101.                 $params = array(
  5102.                     "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  5103.                     "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  5104.                     "date" => $pastDate->format("y-m-d"),
  5105.                     "heure" => $pastDate->format("H:i"),
  5106.                     'clientPhone' => $client->getPhone(),
  5107.                     'clientCivilite' => $client->getCivilite(),
  5108.                     'clientNom' => $client->getLastname(),
  5109.                     'clientPrenom' => $client->getName(),
  5110.                     'clientPostal' => $client->getPostal(),
  5111.                     'clientMail' => $client->getMail(),
  5112.                     "birthdate" => $rdv->getIdClient()->getBirthdate()->format("y-m-d"),
  5113.                     "mail" => $rdv->getIdClient()->getMail(),
  5114.                     "phone" => $rdv->getIdClient()->getPhone(),
  5115.                     "motif" => $rdv->getIdMotif()->getTitre(),
  5116.                     "address" => $rdv->getIdCentre()->getAddress(),
  5117.                     "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getLastName() . ' ' $rdv->getIdAudio()->getName(),
  5118.                     "newRdvDate" => substr($smsDate010),
  5119.                     "newRdvHour" => substr($smsDate1115),
  5120.                     "centerName" => $rdv->getIdCentre()->getName(),
  5121.                     "centerAddress" => $rdv->getIdCentre()->getAddress(),
  5122.                     "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  5123.                     'titre' => "Modification de Rendez-vous My Audio de {$rdv->getIdClient()->getLastname()}",
  5124.                     "urlPro" => "{$_ENV['BASE_logiciel']}",
  5125.                     "idPatient" => $rdv->getIdClient()->getId(),
  5126.                 );
  5127.                 $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  5128.                 $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  5129.                 if ($rdv->getIdAudio()->getModifRdvMail()) {
  5130.                     $subject "🔀 Rendez-vous My Audio modifié par " $client->getCivilite() . " " $client->getName() . " " $client->getLastname();
  5131.                     $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject185);
  5132.                 }
  5133.                 $subjectMyAudio "🔀 Le patient " $client->getCivilite() . " " $client->getName() . " " $client->getLastname() . "  a modifié son rendez-vous My Audio";
  5134.                 $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subjectMyAudio204);
  5135.                 if ($rdv->getIdAudio()->getModifRdvSms()) {
  5136.                     $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.";
  5137.                     $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  5138.                 }
  5139.             }
  5140.         } else if ($rdv->getIdEtat()->getId() == 2) {
  5141.             $params = array(
  5142.                 "date" => substr($smsDate010),
  5143.                 "heure" => substr($smsDate1115),
  5144.                 "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  5145.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  5146.                 "motif" => $rdv->getIdMotif()->getTitre(),
  5147.                 "centerAddress" => $rdv->getIdCentre()->getAddress(),
  5148.                 "centerPostal" => $rdv->getIdCentre()->getPostale(),
  5149.                 "centerCity" => $rdv->getIdCentre()->getCity(),
  5150.                 "centerName" => $rdv->getIdCentre()->getName(),
  5151.                 "clientNom" => $rdv->getIdClient()->getLastname(),
  5152.                 "clientPrenom" => $rdv->getIdClient()->getName(),
  5153.                 "clientMail" => $rdv->getIdClient()->getMail(),
  5154.                 "clientPhone" => $rdv->getIdClient()->getPhone(),
  5155.                 'titre' => "Annulation du Rendez-vous avec le patient {$rdv->getIdClient()->getLastname()}",
  5156.                 "proUrl" => "{$_ENV['BASE_logiciel']}",
  5157.                 "idPatient" => $rdv->getIdClient()->getId(),
  5158.             );
  5159.             $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  5160.             $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  5161.             if ($rdv->getIdAudio()->getModifRdvMail()) {
  5162.                 $subject "❌ Annulation du rendez-vous par le patient " $client->getCivilite() . " " $client->getName() . " " $client->getLastname();
  5163.                 $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject187);
  5164.             }
  5165.             $subject "❌ Annulation du rendez-vous par le patient " $client->getCivilite() . " " $client->getName() . " " $client->getLastname();
  5166.             $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject195);
  5167.             if ($rdv->getIdAudio()->getModifRdvSms()) {
  5168.                 $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.";
  5169.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  5170.             }
  5171.         }
  5172.         $entityManager->flush();
  5173.         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"]))) {
  5174.             $birth \DateTime::createFromFormat("Y-m-d"$data["birthday_patient"]);
  5175.             if (is_null($rdv->getIdClientTemp())) {
  5176.                 $clientRDV $this->getDoctrine()
  5177.                     ->getRepository(Client::class)
  5178.                     ->findOneBy(['id' => $rdv->getIdClient()->getId()]);
  5179.                 $clientRDV->setName($data["prenom_patient"]);
  5180.                 $clientRDV->setLastname($data["nom_patient"]);
  5181.                 $clientRDV->setBirthdate($birth);
  5182.                 $clientRDV->setMail($data["mail_patient"]);
  5183.                 $clientRDV->setPhone($data["portable_patient"]);
  5184.                 $clientRDV->setPhoneFixe($data["fixe_patient"]);
  5185.             } else {
  5186.                 $clientRDV $this->getDoctrine()
  5187.                     ->getRepository(ClientTemp::class)
  5188.                     ->findOneBy(['id' => $rdv->getIdClientTemp()->getId()]);
  5189.                 $clientRDV->setName($data["prenom_patient"]);
  5190.                 $clientRDV->setLastname($data["nom_patient"]);
  5191.                 $clientRDV->setBirthdate($birth);
  5192.                 $clientRDV->setMail($data["mail_patient"]);
  5193.                 $clientRDV->setPhone($data["portable_patient"]);
  5194.                 $clientRDV->setPhoneFixe($data["fixe_patient"]);
  5195.             }
  5196.             $entityManager->flush();
  5197.         }
  5198.         if (is_null($rdv->getIdClient())) {
  5199.             $prenom_patient $rdv->getIdClientTemp()->getName();
  5200.             $nom_patient $rdv->getIdClientTemp()->getLastname();
  5201.             $mail_patient $rdv->getIdClientTemp()->getMail();
  5202.             $portable_patient $rdv->getIdClientTemp()->getPhone();
  5203.             $fixe_patient $rdv->getIdClientTemp()->getPhoneFixe();
  5204.             $birthday $rdv->getIdClientTemp()->getBirthdate();
  5205.         } elseif (is_null($rdv->getIdClientTemp())) {
  5206.             $prenom_patient =  $rdv->getIdClient()->getName();
  5207.             $nom_patient $rdv->getIdClient()->getLastname();
  5208.             $mail_patient $rdv->getIdClient()->getMail();
  5209.             $portable_patient $rdv->getIdClient()->getPhone();
  5210.             $fixe_patient $rdv->getIdClient()->getPhoneFixe();
  5211.             $birthday $rdv->getIdClient()->getBirthdate();
  5212.         } else {
  5213.             $prenom_patient "";
  5214.             $nom_patient "";
  5215.             $mail_patient "";
  5216.             $portable_patient "";
  5217.             $fixe_patient "";
  5218.             $birthday "";
  5219.         }
  5220.         return new Response(json_encode(([
  5221.             "id" => $rdv->getId(),
  5222.             "motif_id" => $rdv->getIdMotif()->getId(),
  5223.             "motif_libelle" => $rdv->getIdMotif()->getTitre(),
  5224.             "audio_id" => $rdv->getIdAudio()->getId(),
  5225.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  5226.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  5227.             "fullName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  5228.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  5229.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  5230.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  5231.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  5232.             "centre_name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : null,
  5233.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  5234.             "etat_id" => $rdv->getIdEtat()->getId(),
  5235.             "date" => $rdv->getDate(),
  5236.             "comment" => $rdv->getComment(),
  5237.             "note" => $rdv->getNote(),
  5238.             "review" => $rdv->getReview(),
  5239.             "prenom_patient" => $prenom_patient,
  5240.             "nom_patient" => $nom_patient,
  5241.             "mail_patient" => $mail_patient,
  5242.             "portable_patient" => $portable_patient,
  5243.             "fixe_patient" => $fixe_patient,
  5244.             "birthday" => $birthday,
  5245.             "status" => 200,
  5246.         ])));
  5247.     }
  5248.     /**
  5249.      * @Route("/rdv/{id}/supp", name="suppRdvByID", methods={"PUT"})
  5250.      */
  5251.     public function suppRdvByID(PublicFunction $publicFunctionRdv $rdvRequest $requestGoogleCalendarService $googleCalendarRdvSmsService $rdvSms): Response
  5252.     {
  5253.         $pastDate $rdv->getDate();
  5254.         $data json_decode($request->getContent(), true);
  5255.         $entityManager $this->getDoctrine()->getManager();
  5256.         if (!isset($data["token"])) {
  5257.             return new Response(json_encode([
  5258.                 "message" => "Pas de token n'a été spécifié",
  5259.                 "status" => 401,
  5260.             ]), 401);
  5261.         }
  5262.         /** @var Token */
  5263.         $token $this->getDoctrine()
  5264.             ->getRepository(Token::class)
  5265.             ->findOneBy(['token' => $data["token"]]);
  5266.         if (!$token) {
  5267.             return new Response(json_encode([
  5268.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  5269.                 "status" => 404,
  5270.             ]), 404);
  5271.         }
  5272.         // get token age
  5273.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  5274.         // if the token if older than 7 days
  5275.         if ($dateDiff->7) {
  5276.             $entityManager->remove($token);
  5277.             $entityManager->flush();
  5278.             return $this->json([
  5279.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  5280.                 'path' => 'src/Controller/ClientController.php',
  5281.                 "status" => 401,
  5282.             ], 401);
  5283.         }
  5284.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  5285.             return new Response(json_encode([
  5286.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  5287.                 "status" => 404,
  5288.             ]), 404);
  5289.         }
  5290.         // delete google agenda event
  5291.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  5292.             ->findBy(array('rdv' => $rdv));
  5293.         //dd($rdvEvents);
  5294.         $synchronisationCosium $this->getDoctrine()->getRepository(SynchronisationCosium::class)->findOneBy(["audio" => $rdv->getIdAudio()->getId()]);
  5295.         $cosiumCenter $this->getDoctrine()->getRepository(CosiumCenter::class)->findBy(["synchronisationCosium" => $synchronisationCosium"center" => $rdv->getIdCentre()]);
  5296.         if ($cosiumCenter) {
  5297.             $this->clientCosiumService->deleteRdv($synchronisationCosium$rdv);
  5298.         }
  5299.         foreach ($rdvEvents as $rdvEvent) {
  5300.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  5301.             $googleCalendar->deleteEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId());
  5302.             $entityManager->remove($rdvEvent);
  5303.             $entityManager->flush();
  5304.         }
  5305.         $etat $this->getDoctrine()
  5306.             ->getRepository(EtatRdv::class)
  5307.             ->findOneBy(['id' => 2]);
  5308.         if ($etat == null) {
  5309.             return new Response(json_encode(([
  5310.                 'message' => 'Error, no etat found at this id',
  5311.                 'path' => 'src/Controller/TrustedUserController.php',
  5312.                 "status" => 400,
  5313.             ])), 400);
  5314.         }
  5315.         $rdv->setIdEtat($etat);
  5316.         $rdv->setCacher(1);
  5317.         ////// SMSEMAIL A décommenter pour activer l'envoi de SMS + MAIL pour modification annulation de RDV, coté audio / client SMSEMAIL ////
  5318.         $date $rdv->getDate();
  5319.         $smsDate $date->format('d-m-Y H:i');
  5320.         $oldDate $pastDate->format('d-m-Y H:i');
  5321.         $locale 'fr_FR';
  5322.         $formatter = new IntlDateFormatter(
  5323.             $locale,
  5324.             IntlDateFormatter::FULL,
  5325.             IntlDateFormatter::SHORT,
  5326.             null,
  5327.             IntlDateFormatter::GREGORIAN,
  5328.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  5329.         );
  5330.         $smsDateLongFormat $formatter->format($date);
  5331.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  5332.         $frenchDate ucfirst($frenchDate);
  5333.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  5334.         // notif client
  5335.         if ($rdv->getIdEtat()->getId() != 2) {
  5336.             $params = array(
  5337.                 "lienModifier" => "{$_ENV['BASE_client']}mes-rendez-vous",
  5338.                 "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  5339.                 "date" => $smsDateLongFormat,
  5340.                 "heure" => substr($smsDate1115),
  5341.                 "motif" => $rdv->getIdMotif()->getTitre(),
  5342.                 "centerName" => $rdv->getIdCentre()->getName(),
  5343.                 "centerAddress" => $rdv->getIdCentre()->getAddress(),
  5344.                 "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  5345.                 "audioMail" => $rdv->getIdAudio()->getMail(),
  5346.                 "centerPhone" => $rdv->getIdCentre()->getPhone(),
  5347.                 "centerCity" => $rdv->getIdCentre()->getCity(),
  5348.                 "clientEmail" => $client->getMail(),
  5349.                 "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  5350.                 'titre' => 'Votre rendez-vous est modifié pour le',
  5351.                 'frenchDate' => $frenchDate
  5352.             );
  5353.             $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  5354.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject205);
  5355.             $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.";
  5356.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  5357.             // creer un mail de notif pour myAudio + créé le template LP | MA | RR - Modification du RDV - Centre Auditif - MyAudio
  5358.             $subjectMyaudio "Rendez-vous My Audio a été modifié par l'audioprothésiste " $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName();
  5359.             $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$client->getName() . ' ' $client->getLastName(), $subjectMyaudio206);
  5360.         }
  5361.         //     //// == suppression
  5362.         else if ($rdv->getIdEtat()->getId() == 2) {
  5363.             $params = array(
  5364.                 "date" => substr($smsDate010),
  5365.                 "lien" => "{$_ENV['BASE_client']}search",
  5366.                 "heure" => substr($smsDate1115),
  5367.                 "patientName" => $client->getLastName() . ' ' $client->getName(),
  5368.                 'titre' => 'Votre rendez-vous est annulé :',
  5369.                 'centerName' => $rdv->getIdCentre()->getName(),
  5370.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  5371.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  5372.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  5373.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  5374.                 "clientEmail" => $client->getMail() ?? '',
  5375.                 "clientPhone" => $client->getPhone() ?? '',
  5376.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  5377.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  5378.                 'motif' => $rdv->getIdMotif()->getTitre(),
  5379.             );
  5380.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  5381.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject188);
  5382.             $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  5383.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  5384.             // creer un mail de notif pour myAudio + créé le template LP | MA | RR - Annlation du RDV - Centre Auditif - MyAudio
  5385.             $subjectMyaudio $rdv->getIdCentre()->getName() . " a annulé un rendez-vous My Audio avec " $client->getName() . ' ' $client->getLastName();
  5386.             $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$client->getName() . ' ' $client->getLastName(), $subjectMyaudio207);
  5387.         }
  5388.         //notif Audio
  5389.         if ($rdv->getIdEtat()->getId() != 2) {
  5390.             $params = array(
  5391.                 "lienModifier" => "{$_ENV['BASE_logiciel']}rdv",
  5392.                 "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  5393.                 "date" => substr($smsDate010),
  5394.                 "frenchDate" => $frenchDate,
  5395.                 "heure" => substr($smsDate1115),
  5396.                 'motif' => $rdv->getIdMotif()->getTitre(),
  5397.                 'clientPhone' => $client->getPhone(),
  5398.                 'clientNom' => $client->getLastname(),
  5399.                 'clientPrenom' => $client->getName(),
  5400.                 'clientCivilite' => $client->getCivilite(),
  5401.                 'clientPostal' => $client->getPostal(),
  5402.                 'clientMail' => $client->getMail(),
  5403.                 'centerName' => $rdv->getIdCentre()->getName(),
  5404.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  5405.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  5406.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  5407.                 'idPatient' => $client->getId(),
  5408.                 'proUrl' => "{$_ENV['BASE_logiciel']}",
  5409.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  5410.                 'titre' => 'Votre rendez-vous est modifié pour le :'
  5411.             );
  5412.             $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  5413.             $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  5414.             if ($rdv->getIdAudio()->getModifRdvMail()) {
  5415.                 $subject "🔀 Rendez-vous My Audio modifié du " $frenchDate " à " substr($smsDate1115);
  5416.                 $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject186);
  5417.             }
  5418.             if ($rdv->getIdAudio()->getModifRdvSms()) {
  5419.                 $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.";
  5420.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  5421.             }
  5422.         } else if ($rdv->getIdEtat()->getId() == 2) {
  5423.             /* $params = array(  
  5424.                     "date" => substr($smsDate, 0, 10),
  5425.                     "lien"=> "{$_ENV['BASE_client']}search",
  5426.                     "heure" =>substr($smsDate, 11, 15),
  5427.                     "patientName" => $client->getLastName(),
  5428.                     'titre' => 'Votre rendez-vous est annulé :',
  5429.                     'centerName' => $rdv->getIdCentre()->getName(),
  5430.                     'centerPostal' => $rdv->getIdCentre()->getPostale(),
  5431.                     'centerCity' => $rdv->getIdCentre()->getCity(),
  5432.                     'centerAddress' => $rdv->getIdCentre()->getAddress(),
  5433.                     'centerPhone' => $rdv->getIdCentre()->getPhone(),
  5434.                     'audioproName' => $rdv->getIdAudio()->getCivilite().' '. $rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(),                    
  5435.                     'audioMail' => $rdv->getIdAudio()->getMail(),
  5436.                     'motif' => $rdv->getIdMotif()->getTitre(),
  5437.                 );
  5438.                 $subject = "Rendez-vous My Audio annulé avec " . $rdv->getIdCentre()->getName();
  5439.                 $publicFunction->sendEmail($params, $rdv->getIdAudio()->getMail(), $rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(), $subject, 188 );
  5440.                 $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.";
  5441.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $rdv->getIdAudio()->getPhone());
  5442.                 */
  5443.         }
  5444.         // delete sms notification     
  5445.         $rdvSms->deleteAssociatedRdvSms($rdv);
  5446.         // delete client device
  5447.         /*$clientDevice = $this->getDoctrine()->getRepository(ClientDevice::class)->findOneBy(['rdv' => $rdv]);
  5448. if($clientDevice)
  5449. {
  5450. if ($client instanceof Client) {
  5451.     $nextRdvs = $this->getDoctrine()
  5452.         ->getRepository(Rdv::class)
  5453.         ->findBy([
  5454.             "id_client" => $rdv->getIdClient(),
  5455.             "id_motif" => ['106', '107', '108', '109'] 
  5456.         ]);
  5457.         $client->setClientStatus(null);
  5458. } elseif ($client instanceof ClientTemp) {
  5459.  $nextRdvs = $this->getDoctrine()
  5460.         ->getRepository(Rdv::class)
  5461.         ->findBy([
  5462.             "id_client_temp" => $rdv->getIdClientTemp(),
  5463.             "id_motif" => ['106', '107', '108', '109'] 
  5464.         ]);
  5465.         $client->setClientStatus(null);
  5466.     } 
  5467.     $locale = 'fr_FR';
  5468.     $fmt = new IntlDateFormatter($locale, IntlDateFormatter::FULL, IntlDateFormatter::NONE);
  5469.     $fmt->setPattern("EEEE dd MMMM yyyy"); 
  5470.     if($nextRdvs){
  5471.     $params = array(  
  5472.                 "title" => "Affectation de votre appareil et programmation de vos rendez-vous",
  5473.                 "centerName" => "{$rdv->getIdCentre()->getName()}",
  5474.                 "audioName" => "{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastName()}",
  5475.                 "centerAddress" => "{$rdv->getIdCentre()->getAddress()}",
  5476.                 "device" => "{$clientDevice->getDevice()->getModel()}",
  5477.                 "ears" => "{$clientDevice->getSettingDevice()->getName()}",
  5478.                 "rdvOneDate" => "{$fmt->format($nextRdvs['0']->getDate())}",
  5479.                 "rdvOneHour" => "{$nextRdvs['0']->getDate()->format('H:i')}",
  5480.                 "rdvTwoDate" => "{$fmt->format($nextRdvs['1']->getDate())}",
  5481.                 "rdvTwoHour" => "{$nextRdvs['1']->getDate()->format('H:i')}",
  5482.                 "rdvThreeDate" => "{$fmt->format($nextRdvs['2']->getDate())}",
  5483.                 "rdvThreeHour" => "{$nextRdvs['2']->getDate()->format('H:i')}",
  5484.                 "rdvFourDate" => "{$fmt->format($nextRdvs['3']->getDate())}",
  5485.                 "rdvFourHour" => "{$nextRdvs['3']->getDate()->format('H:i')}",
  5486.             );
  5487.     
  5488.             $publicFunction->sendEmail($params, $client->getMail(), $client->getName().' '.$client->getLastName(), "Annulation de vos prochains RDV", 162 );
  5489.         }
  5490.     foreach($nextRdvs as $rdv)
  5491.     {
  5492.         $entityManager->remove($rdv);
  5493.     }
  5494.     $entityManager->persist($client);
  5495.     $entityManager->remove($clientDevice);
  5496.     $entityManager->flush();
  5497. }*/
  5498.         // Before deleting, publish the deletion event
  5499.         $this->mercure->publishRdvDeletion($rdv);
  5500.         $entityManager->flush();
  5501.         return new Response(json_encode(([
  5502.             "id" => $rdv->getId(),
  5503.             "motif_id" => $rdv->getIdMotif()->getId(),
  5504.             "motif_libelle" => $rdv->getIdMotif()->getTitre(),
  5505.             "audio_id" => $rdv->getIdAudio()->getId(),
  5506.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  5507.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  5508.             "fullName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  5509.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  5510.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  5511.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  5512.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  5513.             "centre_name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : null,
  5514.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  5515.             "etat_id" => $rdv->getIdEtat()->getId(),
  5516.             "date" => $rdv->getDate(),
  5517.             "comment" => $rdv->getComment(),
  5518.             "note" => $rdv->getNote(),
  5519.             "review" => $rdv->getReview(),
  5520.             "status" => 200,
  5521.         ])));
  5522.     }
  5523.     /**
  5524.      * @Route("/rdv/calendar", name="postRdvCalendar", methods={"POST"})
  5525.      */
  5526.     public function postRdvCalendar(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendarRdvSmsService $rdvSmsPublisherInterface $publisher): Response
  5527.     {
  5528.         $data json_decode($request->getContent(), true);
  5529.         if (!isset($data["token"])) {
  5530.             return new Response(json_encode([
  5531.                 "message" => "Pas de token n'a été spécifié",
  5532.                 "status" => 401,
  5533.             ]), 401);
  5534.         }
  5535.         $entityManager $this->getDoctrine()->getManager();
  5536.         /** @var Token */
  5537.         $token $this->getDoctrine()
  5538.             ->getRepository(Token::class)
  5539.             ->findOneBy(['token' => $data["token"]]);
  5540.         if (!$token) {
  5541.             return new Response(json_encode([
  5542.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  5543.                 "status" => 404,
  5544.             ]), 404);
  5545.         }
  5546.         // get token age
  5547.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  5548.         // if the token if older than 7 days
  5549.         if ($dateDiff->7) {
  5550.             $entityManager->remove($token);
  5551.             $entityManager->flush();
  5552.             return $this->json([
  5553.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  5554.                 'path' => 'src/Controller/ClientController.php',
  5555.                 "status" => 401,
  5556.             ], 401);
  5557.         }
  5558.         // makes the rdv
  5559.         $rdv = new Rdv();
  5560.         if ($token->getIdAudio()) {
  5561.             //if the token if for an audio
  5562.             $audio $token->getIdAudio();
  5563.             if ((isset($data["client_id"]))) {
  5564.                 $client $this->getDoctrine()
  5565.                     ->getRepository(Client::class)
  5566.                     ->findOneBy(['id' => $data["client_id"]]);
  5567.             } else {
  5568.                 $client $this->getDoctrine()
  5569.                     ->getRepository(ClientTemp::class)
  5570.                     ->findOneBy(['id' => $data["client_id_temp"]]);
  5571.             }
  5572.             if ($client == null) {
  5573.                 return new Response(json_encode(([
  5574.                     'message' => 'Error, no client found at this id',
  5575.                     'path' => 'src/Controller/RdvController.php',
  5576.                     "status" => 400,
  5577.                 ])), 400);
  5578.             }
  5579.         } elseif ($token->getIdClient()) {
  5580.             //if the token if for a client
  5581.             $client $token->getIdClient();
  5582.             /** @var Audio */
  5583.             $audio $this->getDoctrine()
  5584.                 ->getRepository(Audio::class)
  5585.                 ->findOneBy(['id' => $data["audio_id"]]);
  5586.             if (isset($data["proche_id"])) {
  5587.                 $proche $this->getDoctrine()
  5588.                     ->getRepository(Proches::class)
  5589.                     ->findOneBy(['id' => $data["proche_id"], "id_client" => $client]);
  5590.             }
  5591.             if ($audio == null) {
  5592.                 return new Response(json_encode(([
  5593.                     'message' => 'Error, no audio found at this id',
  5594.                     'path' => 'src/Controller/RdvController.php',
  5595.                     "status" => 400,
  5596.                 ])), 400);
  5597.             }
  5598.         } else {
  5599.             return new Response(json_encode(([
  5600.                 'message' => 'Error, token is not an audio token',
  5601.                 'path' => 'src/Controller/RdvController.php',
  5602.                 "status" => 400,
  5603.             ])), 400);
  5604.         }
  5605.         $rdv->setIdAudio($audio);
  5606.         if (isset($proche)) {
  5607.             $rdv->setIdProche($proche);
  5608.         }
  5609.         if (isset($data["client_id_temp"])) {
  5610.             $rdv->setIdClientTemp($client);
  5611.         } else {
  5612.             $rdv->setIdClient($client);
  5613.         }
  5614.         $rdv->setCacher(0);
  5615.         /** @var Centre */
  5616.         if (isset($data["centre_id"])) {
  5617.             $centre $this->getDoctrine()
  5618.                 ->getRepository(Centre::class)
  5619.                 ->findOneBy(['id' => $data["centre_id"]]);
  5620.             if ($centre == null) {
  5621.                 return new Response(json_encode(([
  5622.                     'message' => 'Error, no centre found at this id',
  5623.                     'path' => 'src/Controller/RdvController.php',
  5624.                     "status" => 400,
  5625.                 ])), 400);
  5626.             }
  5627.             /** @var AudioCentre */
  5628.             $liaison $this->getDoctrine()
  5629.                 ->getRepository(AudioCentre::class)
  5630.                 ->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
  5631.             if ($liaison == null) {
  5632.                 return new Response(json_encode(([
  5633.                     'message' => 'Error, audio isnt part of the centre',
  5634.                     'path' => 'src/Controller/RdvController.php',
  5635.                     "status" => 400,
  5636.                 ])), 400);
  5637.             }
  5638.             $rdv->setIdCentre($centre);
  5639.         } elseif (isset($data["lieu_id"]) && $audio->getIsIndie()) {
  5640.             // tries to set the lieu if it's an audio indie
  5641.             $lieu $this->getDoctrine()
  5642.                 ->getRepository(Lieu::class)
  5643.                 ->findOneBy(['id' => $data["lieu_id"], 'id_gerant' => $data["audio_id"]]);
  5644.             if ($lieu == null) {
  5645.                 return new Response(json_encode(([
  5646.                     'message' => 'Error, no lieu found at this id',
  5647.                     'path' => 'src/Controller/RdvController.php',
  5648.                     "status" => 400,
  5649.                 ])), 400);
  5650.             }
  5651.             $rdv->setIdLieu($lieu);
  5652.         } else {
  5653.             return new Response(json_encode(([
  5654.                 'message' => 'Error, no lieu/centre id',
  5655.                 'path' => 'src/Controller/RdvController.php',
  5656.                 "status" => 400,
  5657.             ])), 400);
  5658.         }
  5659.         /** @var Motif */
  5660.         $motif $this->getDoctrine()
  5661.             ->getRepository(Motif::class)
  5662.             ->find($data["motif_id"]);
  5663.         if ($motif == null) {
  5664.             return new Response(json_encode(([
  5665.                 'message' => 'Error, no motif found at this id',
  5666.                 'path' => 'src/Controller/RdvController.php',
  5667.                 "status" => 400,
  5668.             ])), 400);
  5669.         }
  5670.         /** @var AudioMotif */
  5671.         $audioMotif $this->getDoctrine()
  5672.             ->getRepository(AudioMotif::class)
  5673.             ->findOneBy(["id_audio" => $audio->getId(), "id_motif" => $data["motif_id"]]);
  5674.         if ($audioMotif == null) {
  5675.             return new Response(json_encode(([
  5676.                 'message' => 'Error, no motif of this id found at this audio',
  5677.                 'path' => 'src/Controller/RdvController.php',
  5678.                 "status" => 400,
  5679.             ])), 400);
  5680.         }
  5681.         // remove the taken schedule by rdv to make sure there is no overlap
  5682.         $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  5683.         if (isset($data["note"])) {
  5684.             $rdv->setNote($data["note"]);
  5685.         }
  5686.         // test if the audio is available
  5687.         /*   if (isset($data["lieu_id"]) && $audio->getIsIndie()){
  5688.             if ($publicFunction->calculScheduleFitDate($audio, $date, $audioMotif->getDuration(), null, $lieu) == false) {
  5689.                 return new Response(json_encode(([
  5690.                     'message' => 'Error, no timestamp found at this time',
  5691.                     'path' => 'src/Controller/RdvController.php',
  5692.                     "status" => 400,
  5693.                 ])), 400);
  5694.             }
  5695.         } else {
  5696.             if ($publicFunction->calculScheduleFitDate($audio, $date, $audioMotif->getDuration(), $centre , null) == true) {
  5697.                 return new Response(json_encode(([
  5698.                     'message' => 'Error, no timestamp found at this time',
  5699.                     'path' => 'src/Controller/RdvController.php',
  5700.                     "status" => 400,
  5701.                 ])), 400);
  5702.             }
  5703.         }*/
  5704.         $rdv->setDate($date);
  5705.         $rdv->setDateCreation(\DateTime::createFromFormat("d/m/Y H:i"date('d/m/Y H:i')));
  5706.         /** @var EtatRdv */
  5707.         $etat $this->getDoctrine()
  5708.             ->getRepository(EtatRdv::class)
  5709.             ->findOneBy(['id' => $data["etat_id"]]);
  5710.         if ($etat == null) {
  5711.             return new Response(json_encode(([
  5712.                 'message' => 'Error, no etat found at this id',
  5713.                 'path' => 'src/Controller/RdvController.php',
  5714.                 "status" => 400,
  5715.             ])), 400);
  5716.         }
  5717.         $rdv->setIdEtat($etat);
  5718.         $rdv->setIdMotif($motif);
  5719.         $rdv->setDuration($data["duree"]);
  5720.         $rdv->setIsAbsence($data["is_absence"]);
  5721.         $entityManager $this->getDoctrine()->getManager();
  5722.         $entityManager->persist($rdv);
  5723.         $entityManager->flush();
  5724.         $date $rdv->getDate();
  5725.         $smsDate $date->format('d-m-Y H:i');
  5726.         $locale 'fr_FR';
  5727.         $formatter = new IntlDateFormatter(
  5728.             $locale,
  5729.             IntlDateFormatter::FULL,
  5730.             IntlDateFormatter::SHORT,
  5731.             null,
  5732.             IntlDateFormatter::GREGORIAN,
  5733.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  5734.         );
  5735.         $smsDateLongFormat $formatter->format($date);
  5736.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  5737.         // client notif mail Sms
  5738.         // we send parametre for the trait methid
  5739.         //$params = $this->emailNotificationService->prepareEmailParams($user);
  5740.         // send email notifcation
  5741.         //$this->emailNotificationService->sendEmail($params, 'admin@example.com', 'Nouvelle inscription à My Audio Pro', 1);
  5742.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  5743.         $frenchDate ucfirst($frenchDate);
  5744.         $params = array(
  5745.             "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  5746.             "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  5747.             "date" => $smsDateLongFormat,
  5748.             "prenom" => $client->getName(),
  5749.             //"heure" => $smsDatee,
  5750.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  5751.             "centerName" => $rdv->getIdCentre()->getName(),
  5752.             "centerAddress" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  5753.             "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  5754.             "centerCity" => $rdv->getIdCentre()->getCity(),
  5755.             "motif" => $rdv->getIdMotif()->getTitre(),
  5756.             "RdvDate" => substr($smsDate010) . " à "  substr($smsDate1115),
  5757.             "audioName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  5758.             "clientMail" => $client->getMail(),
  5759.             "clientPhone" => $client->getPhone(),
  5760.             'titre' => "Votre rendez-vous est validé le " substr($smsDate010) . " à "  substr($smsDate1115),
  5761.             "address" => $rdv->getIdCentre()->getAddress(),
  5762.             "postal" => $rdv->getIdCentre()->getPostale(),
  5763.             "city" => $rdv->getIdCentre()->getCity(),
  5764.             "clientEmail" => $client->getMail(),
  5765.             "clientPassword" => isset($data["passwordGenerated"]) ? $data["passwordGenerated"] : null,
  5766.             "clientAddress" => $client->getAddress(),
  5767.             "clientPostal" => $client->getPostal(),
  5768.             "clientCity" => $client->getCity(),
  5769.             "audioName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  5770.             "frenchDate" => $frenchDate,
  5771.             "heure" => substr($smsDate1115),
  5772.             "centerName" => $rdv->getIdCentre()->getName(),
  5773.             "audioMail" => $rdv->getIdAudio()->getMail(),
  5774.             "modifUrl" => "{$_ENV['BASE_client']}mes-rendez-vous",
  5775.         );
  5776.         $subject "Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  5777.         $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject181);
  5778.         $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.";
  5779.         // $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $client->getPhone());
  5780.         // audio Notif mail SMS
  5781.         /* $params = array(  
  5782.                         "lienModifer" =>"{$_ENV['BASE_logiciel']}rdv",
  5783.                         "lienAnnule"=> "{$_ENV['BASE_logiciel']}rdv",
  5784.                         "date" => substr($smsDate, 0, 10),
  5785.                         "heure" =>substr($smsDate, 11, 15),
  5786.                         'motif' => $rdv->getIdMotif()->getTitre(),
  5787.                         'clientPhone'=> $client->getPhone(),
  5788.                         'clientNom' =>$client->getLastname(),
  5789.                         'clientPrenom' =>$client->getName(),
  5790.                         'clientCivilite' => $client->getCivilite(),
  5791.                         'clientPostal' => $client->getPostal(),
  5792.                         'clientMail' => $client->getMail(),
  5793.                         'centerName' => $rdv->getIdCentre()->getName(),
  5794.                         'centerPostal' => $rdv->getIdCentre()->getPostale(),
  5795.                         'centerCity' => $rdv->getIdCentre()->getCity(),
  5796.                         'centerAddress' => $rdv->getIdCentre()->getAddress(),
  5797.                         'idPatient' => $client->getId(),
  5798.                         'proUrl' => "{$_ENV['BASE_logiciel']}",
  5799.                         'audioproName' => $rdv->getIdAudio()->getCivilite().' '.$rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(),
  5800.                         'titre' => 'Votre rendez-vous est modifié pour le :'
  5801.                     );
  5802.         $subject = "🔀 Rendez-vous My Audio modifié du ". $frenchDate . " à " . substr($smsDate, 11, 15);
  5803.         $publicFunction->sendEmail($params, $rdv->getIdAudio()->getMail(), $rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(), $subject, 186 );
  5804.         $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.";
  5805.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $rdv->getIdAudio()->getPhone());*/
  5806.         // google calendar post
  5807.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  5808.             ->findBy(array('audio' => $audio->getId()));
  5809.         $data['rdv'] = $rdv->getId();
  5810.         $synchronisationCosium $this->getDoctrine()->getRepository(SynchronisationCosium::class)->findOneBy(["audio" => $audio->getId()]);
  5811.         $cosiumCenter $this->getDoctrine()->getRepository(CosiumCenter::class)->findOneBy(["synchronisationCosium" => $synchronisationCosium"center" => $rdv->getIdCentre()]);
  5812.         if ($cosiumCenter) {
  5813.             $this->clientCosiumService->createAgenda($synchronisationCosium$rdv$cosiumCenter);
  5814.         }
  5815.         foreach ($synchronisations as $synchronisation) {
  5816.             if (!$synchronisation->getIsDeleted()) {
  5817.                 try {
  5818.                     $googleCalendar->checkAndRefreshAccessToken($synchronisation);
  5819.                     $googleCalendar->createEvent($synchronisation$data);
  5820.                 } catch (\Exception $e) {
  5821.                     error_log('Error refreshing access token or creating event: ' $e->getMessage());
  5822.                 }
  5823.             }
  5824.         }
  5825.         // create schedule notification sms
  5826.         $rdvSms->storeRdvSmsNotifications($rdv);
  5827.         if ($rdv->getClientDevice()) {
  5828.             $nextRdv $this->getDoctrine()
  5829.                 ->getRepository(Rdv::class)
  5830.                 ->find($rdv->getClientDevice()->getRdv()->getId());
  5831.             if ($nextRdv->getIdClientTemp()) {
  5832.                 $nextRdvs $this->getDoctrine()
  5833.                     ->getRepository(Rdv::class)
  5834.                     ->findBy([
  5835.                         "id_client_temp" => $nextRdv->getIdClientTemp(),
  5836.                         "id_motif" => ['106''107''108''109']
  5837.                     ]);
  5838.             } else {
  5839.                 $nextRdvs $this->getDoctrine()
  5840.                     ->getRepository(Rdv::class)
  5841.                     ->findBy([
  5842.                         "id_client" => $nextRdv->getIdClient(),
  5843.                         "id_motif" => ['106''107''108''109']
  5844.                     ]);
  5845.             }
  5846.             $mappedNextRdvs array_map(function ($rdv) {
  5847.                 return [
  5848.                     'id' => $rdv->getId(),
  5849.                     'date' => $rdv->getDate()->format('d-m-Y'),
  5850.                     'hours' => $rdv->getDate()->format('H:i'),
  5851.                     'duration' => $rdv->getDuration(),
  5852.                     "motif_id" => $rdv->getIdMotif()->getId(),
  5853.                     "motif_titre" => $rdv->getIdMotif()->getTitre(),
  5854.                     "duration" => $rdv->getDuration(),
  5855.                 ];
  5856.             }, $nextRdvs);
  5857.         }
  5858. $token $this->entityManager
  5859.      ->getRepository(Token::class)
  5860.      ->findOneBy(['token' => $data['token']]);
  5861. $tokenAudioId $token->getIdAudio()->getId();
  5862. $requestAudioId $data['audio_id'] ?? null;
  5863. $requestCenterId $data['center_id'] ?? null;
  5864. // Check audio
  5865. if ($requestAudioId && $requestAudioId == $tokenAudioId) {
  5866.     // Verify center belongs to this audio
  5867.     $centre $this->entityManager
  5868.         ->getRepository(Centre::class)
  5869.         ->findOneBy(['id_gerant' => $tokenAudioId]);
  5870.     if ($centre && $centre->getId() == $requestCenterId) {
  5871.         // All conditions ok → send mercure update
  5872.         $this->mercure->publishRdvUpdate($rdv'created');
  5873.     }
  5874. }
  5875.         return new Response(json_encode(([
  5876.             "id" => $rdv->getId(),
  5877.             "motif_id" => $rdv->getIdMotif()->getId(),
  5878.             "audio_id" => $rdv->getIdAudio()->getId(),
  5879.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  5880.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  5881.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  5882.             "centerName" => $rdv->getIdCentre()->getName(),
  5883.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  5884.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  5885.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  5886.             "duration" => $data["duree"],
  5887.             "etat_id" => $rdv->getIdEtat()->getId(),
  5888.             "date" => $rdv->getDate(),
  5889.             "clientEtatId" => $client->getClientStatus() ? $client->getClientStatus()->getId() : 0,
  5890.             "isClient" => ($client instanceof Client) ? 0,
  5891.             "device" => $rdv->getClientDevice() ? [
  5892.                 "isDevice" => true,
  5893.                 "deviceID" => $rdv->getClientDevice()->getDevice()->getId(),
  5894.                 "clientDeviceID" => $rdv->getClientDevice()->getId(),
  5895.                 "deviceModel" => $rdv->getClientDevice()->getDevice()->getModel(),
  5896.                 "settingName" => $rdv->getClientDevice()->getSettingDevice()->getName(),
  5897.                 "settingDeviceId" => $rdv->getClientDevice()->getSettingDevice()->getSlug(),
  5898.                 "settingSlug" => $rdv->getClientDevice()->getSettingDevice()->getSlug(),
  5899.                 "nextRdvs" => $mappedNextRdvs
  5900.             ] : [
  5901.                 "isDevice" => false
  5902.             ],
  5903.             "comment" => $rdv->getComment(),
  5904.             "review" => $rdv->getReview(),
  5905.             "note" => $rdv->getNote(),
  5906.             "status" => 200,
  5907.         ])));
  5908.     }
  5909.     /**
  5910.      * @Route("/rdv/absence", name="postAbsenceCalendar", methods={"POST"})
  5911.      */
  5912.     public function postAbsenceCalendar(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendar): Response
  5913.     {
  5914.         $data json_decode($request->getContent(), true);
  5915.         if (!isset($data["token"])) {
  5916.             return new Response(json_encode([
  5917.                 "message" => "Pas de token n'a été spécifié",
  5918.                 "status" => 401,
  5919.             ]), 401);
  5920.         }
  5921.         $entityManager $this->getDoctrine()->getManager();
  5922.         /** @var Token */
  5923.         $token $this->getDoctrine()
  5924.             ->getRepository(Token::class)
  5925.             ->findOneBy(['token' => $data["token"]]);
  5926.         if (!$token) {
  5927.             return new Response(json_encode([
  5928.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  5929.                 "status" => 404,
  5930.             ]), 404);
  5931.         }
  5932.         // get token age
  5933.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  5934.         // if the token if older than 7 days
  5935.         if ($dateDiff->7) {
  5936.             $entityManager->remove($token);
  5937.             $entityManager->flush();
  5938.             return $this->json([
  5939.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  5940.                 'path' => 'src/Controller/ClientController.php',
  5941.                 "status" => 401,
  5942.             ], 401);
  5943.         }
  5944.         // makes the rdv
  5945.         $rdv = new Rdv();
  5946.         $audio $token->getIdAudio();
  5947.         $rdv->setIdAudio($audio);
  5948.         /** @var Centre */
  5949.         if (isset($data["centre_id"])) {
  5950.             $centre $this->getDoctrine()
  5951.                 ->getRepository(Centre::class)
  5952.                 ->findOneBy(['id' => $data["centre_id"]]);
  5953.             if ($centre == null) {
  5954.                 return new Response(json_encode(([
  5955.                     'message' => 'Error, no centre found at this id',
  5956.                     'path' => 'src/Controller/RdvController.php',
  5957.                     "status" => 400,
  5958.                 ])), 400);
  5959.             }
  5960.             /** @var AudioCentre */
  5961.             $liaison $this->getDoctrine()
  5962.                 ->getRepository(AudioCentre::class)
  5963.                 ->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
  5964.             if ($liaison == null) {
  5965.                 return new Response(json_encode(([
  5966.                     'message' => 'Error, audio isnt part of the centre',
  5967.                     'path' => 'src/Controller/RdvController.php',
  5968.                     "status" => 400,
  5969.                 ])), 400);
  5970.             }
  5971.             $rdv->setIdCentre($centre);
  5972.         } elseif (isset($data["lieu_id"]) && $audio->getIsIndie()) {
  5973.             // tries to set the lieu if it's an audio indie
  5974.             $lieu $this->getDoctrine()
  5975.                 ->getRepository(Lieu::class)
  5976.                 ->findOneBy(['id' => $data["lieu_id"], 'id_gerant' => $data["audio_id"]]);
  5977.             if ($lieu == null) {
  5978.                 return new Response(json_encode(([
  5979.                     'message' => 'Error, no lieu found at this id',
  5980.                     'path' => 'src/Controller/RdvController.php',
  5981.                     "status" => 400,
  5982.                 ])), 400);
  5983.             }
  5984.             $rdv->setIdLieu($lieu);
  5985.         } else {
  5986.             return new Response(json_encode(([
  5987.                 'message' => 'Error, no lieu/centre id',
  5988.                 'path' => 'src/Controller/RdvController.php',
  5989.                 "status" => 400,
  5990.             ])), 400);
  5991.         }
  5992.         // remove the taken schedule by rdv to make sure there is no overlap
  5993.         $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  5994.         $rdv->setDate($date);
  5995.         $rdv->setDateCreation(\DateTime::createFromFormat("d/m/Y H:i"date('d/m/Y H:i')));
  5996.         /** @var EtatRdv */
  5997.         $etat $this->getDoctrine()
  5998.             ->getRepository(EtatRdv::class)
  5999.             ->findOneBy(['id' => $data["etat_id"]]);
  6000.         if ($etat == null) {
  6001.             return new Response(json_encode(([
  6002.                 'message' => 'Error, no etat found at this id',
  6003.                 'path' => 'src/Controller/RdvController.php',
  6004.                 "status" => 400,
  6005.             ])), 400);
  6006.         }
  6007.         $rdv->setIdEtat($etat);
  6008.         $rdv->setDuration($data["duree"]);
  6009.         $rdv->setIsAbsence($data["is_absence"]);
  6010.         $rdv->setMotifAbsence($data["motif"]);
  6011.         $rdv->setColor($data["color"]);
  6012.         $rdv->setNote($data["note"]);
  6013.         $rdv->setCacher(0);
  6014.         $entityManager $this->getDoctrine()->getManager();
  6015.         $entityManager->persist($rdv);
  6016.         $entityManager->flush();
  6017.         // create google calendar absence event
  6018.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  6019.             ->findBy(array('audio' => $audio->getId()));
  6020.         $data['rdv'] = $rdv->getId();
  6021.         $data['motif_absence'] = $rdv->getMotifAbsence() !== '' $rdv->getMotifAbsence() : "Absence";
  6022.         //        dd($data);
  6023.         foreach ($synchronisations as $synchronisation) {
  6024.             if (!$synchronisation->getIsDeleted()) {
  6025.                 try {
  6026.                     $googleCalendar->checkAndRefreshAccessToken($synchronisation);
  6027.                     $googleCalendar->createAbsenceEvent($synchronisation$data);
  6028.                 } catch (\Google\Service\Exception $e) {
  6029.                     if ($e->getCode() === 403 && str_contains($e->getMessage(), 'insufficientPermissions')) {
  6030.                         error_log("Skipped synchronisation ID {$synchronisation->getId()} due to insufficient permissions.");
  6031.                         continue;
  6032.                     }
  6033.                     throw $e;
  6034.                 }
  6035.             }
  6036.         }
  6037.         return new Response(json_encode(([
  6038.             "id" => $rdv->getId(),
  6039.             "audio_id" => $rdv->getIdAudio()->getId(),
  6040.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  6041.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  6042.             "duration" => $data["duree"],
  6043.             "etat_id" => $rdv->getIdEtat()->getId(),
  6044.             "date" => $rdv->getDate(),
  6045.             "status" => 200,
  6046.         ])));
  6047.     }
  6048.     /**
  6049.      * @Route("/rdv/{id}/absence", name="puttAbsenceCalendar", methods={"PUT"})
  6050.      */
  6051.     public function putAbsenceCalendar(Request $requestRdv $rdvPublicFunction $publicFunctionGoogleCalendarService $googleCalendar): Response
  6052.     {
  6053.         $data json_decode($request->getContent(), true);
  6054.         if (!isset($data["token"])) {
  6055.             return new Response(json_encode([
  6056.                 "message" => "Pas de token n'a été spécifié",
  6057.                 "status" => 401,
  6058.             ]), 401);
  6059.         }
  6060.         $entityManager $this->getDoctrine()->getManager();
  6061.         /** @var Token */
  6062.         $token $this->getDoctrine()
  6063.             ->getRepository(Token::class)
  6064.             ->findOneBy(['token' => $data["token"]]);
  6065.         if (!$token) {
  6066.             return new Response(json_encode([
  6067.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  6068.                 "status" => 404,
  6069.             ]), 404);
  6070.         }
  6071.         // get token age
  6072.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  6073.         // if the token if older than 7 days
  6074.         if ($dateDiff->7) {
  6075.             $entityManager->remove($token);
  6076.             $entityManager->flush();
  6077.             return $this->json([
  6078.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  6079.                 'path' => 'src/Controller/ClientController.php',
  6080.                 "status" => 401,
  6081.             ], 401);
  6082.         }
  6083.         // remove the taken schedule by rdv to make sure there is no overlap
  6084.         if (isset($data["date"])) {
  6085.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  6086.             $rdv->setDate($date);
  6087.         }
  6088.         if (isset($data["duree"])) {
  6089.             $rdv->setDuration($data["duree"]);
  6090.         }
  6091.         if (isset($data["motif"])) {
  6092.             $rdv->setMotifAbsence($data["motif"]);
  6093.         }
  6094.         if (isset($data["color"])) {
  6095.             $rdv->setColor($data["color"]);
  6096.         }
  6097.         if (isset($data["note"])) {
  6098.             $rdv->setNote($data["note"]);
  6099.         }
  6100.         $entityManager $this->getDoctrine()->getManager();
  6101.         $entityManager->flush();
  6102.         $data['rdv'] = $rdv->getId();
  6103.         $data['motif_absence'] = $rdv->getMotifAbsence() !== '' $rdv->getMotifAbsence() : "Absence";
  6104.         $data['note'] = $rdv->getNote();
  6105.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  6106.             ->findBy(array('rdv' => $rdv));
  6107.         foreach ($rdvEvents as $rdvEvent) {
  6108.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  6109.             $googleCalendar->updateAbsenceEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
  6110.         }
  6111.         return new Response(json_encode(([
  6112.             "id" => $rdv->getId(),
  6113.             "audio_id" => $rdv->getIdAudio()->getId(),
  6114.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  6115.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  6116.             "duration" => $rdv->getDuration(),
  6117.             "etat_id" => $rdv->getIdEtat()->getId(),
  6118.             "date" => $rdv->getDate(),
  6119.             "status" => 200,
  6120.         ])));
  6121.     }
  6122.     /**
  6123.      * @Route("/rdv/{id}/calendar", name="editRdvCalendarByID", methods={"PUT"})
  6124.      */
  6125.     public function editRdvCalendarByID(SmsHandler $smsHandlerRdv $rdvRequest $requestGoogleCalendarService $googleCalendarPublicFunction $publicFunctionRdvSmsService $rdvSms): Response
  6126.     {
  6127.         $pastDate $rdv->getDate();
  6128.         $data json_decode($request->getContent(), true);
  6129.         $entityManager $this->getDoctrine()->getManager();
  6130.         if (!isset($data["token"])) {
  6131.             return new Response(json_encode([
  6132.                 "message" => "Pas de token n'a été spécifié",
  6133.                 "status" => 401,
  6134.             ]), 401);
  6135.         }
  6136.         /** @var Token */
  6137.         $token $this->getDoctrine()
  6138.             ->getRepository(Token::class)
  6139.             ->findOneBy(['token' => $data["token"]]);
  6140.         if (!$token) {
  6141.             return new Response(json_encode([
  6142.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  6143.                 "status" => 404,
  6144.             ]), 404);
  6145.         }
  6146.         // get token age
  6147.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  6148.         // if the token if older than 7 days
  6149.         if ($dateDiff->7) {
  6150.             $entityManager->remove($token);
  6151.             $entityManager->flush();
  6152.             return $this->json([
  6153.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  6154.                 'path' => 'src/Controller/ClientController.php',
  6155.                 "status" => 401,
  6156.             ], 401);
  6157.         }
  6158.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  6159.             return new Response(json_encode([
  6160.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  6161.                 "status" => 404,
  6162.             ]), 404);
  6163.         }
  6164.         if (isset($data["etat_id"])) {
  6165.             $etat $this->getDoctrine()
  6166.                 ->getRepository(EtatRdv::class)
  6167.                 ->findOneBy(['id' => $data["etat_id"]]);
  6168.             if ($etat == null) {
  6169.                 return new Response(json_encode(([
  6170.                     'message' => 'Error, no etat found at this id',
  6171.                     'path' => 'src/Controller/TrustedUserController.php',
  6172.                     "status" => 400,
  6173.                 ])), 400);
  6174.             }
  6175.             $rdv->setIdEtat($etat);
  6176.         }
  6177.         if (isset($data["audio_id"])) {
  6178.             $audio $this->getDoctrine()
  6179.                 ->getRepository(Audio::class)
  6180.                 ->findOneBy(['id' => $data["audio_id"]]);
  6181.             if ($audio == null) {
  6182.                 return new Response(json_encode(([
  6183.                     'message' => 'Error, no audio found at this id',
  6184.                     'path' => 'src/Controller/TrustedUserController.php',
  6185.                     "status" => 400,
  6186.                 ])), 400);
  6187.             }
  6188.             $rdv->setIdAudio($audio);
  6189.         }
  6190.         if (isset($data["motif_id"])) {
  6191.             $motif $this->getDoctrine()
  6192.                 ->getRepository(Motif::class)
  6193.                 ->find($data["motif_id"]);
  6194.             if ($motif == null) {
  6195.                 return new Response(json_encode(([
  6196.                     'message' => 'Error, no motif found at this id',
  6197.                     'path' => 'src/Controller/TrustedUserController.php',
  6198.                     "status" => 400,
  6199.                 ])), 400);
  6200.             }
  6201.             $rdv->setIdMotif($motif);
  6202.         }
  6203.         if (isset($data["client_id"])) {
  6204.             $client $this->getDoctrine()
  6205.                 ->getRepository(Client::class)
  6206.                 ->findOneBy(['id' => $data["client_id"]]);
  6207.             if ($client == null) {
  6208.                 return new Response(json_encode(([
  6209.                     'message' => 'Error, no client found at this id',
  6210.                     'path' => 'src/Controller/TrustedUserController.php',
  6211.                     "status" => 400,
  6212.                 ])), 400);
  6213.             }
  6214.             $rdv->setIdClient($client);
  6215.         }
  6216.         if (isset($data["date"])) {
  6217.             // remove the taken schedule by rdv to make sure there is no overlap
  6218.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  6219.             $audioMotif $this->getDoctrine()
  6220.                 ->getRepository(AudioMotif::class)
  6221.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  6222.             if ($audioMotif == null) {
  6223.                 return new Response(json_encode(([
  6224.                     'message' => 'Error, no motif of this id found at this audio',
  6225.                     'path' => 'src/Controller/RdvController.php',
  6226.                     "status" => 400,
  6227.                 ])), 400);
  6228.             }
  6229.             if ($rdv->getIdAudio()->getIsIndie()) {
  6230.                 if ($rdv->getIdCentre()) {
  6231.                     // regular centre audio indie
  6232.                     /** @var AudioCentre */
  6233.                     $liaison $this->getDoctrine()
  6234.                         ->getRepository(AudioCentre::class)
  6235.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  6236.                     if ($liaison == null) {
  6237.                         return new Response(json_encode(([
  6238.                             'message' => 'Error, audio isnt part of the centre',
  6239.                             'path' => 'src/Controller/RdvController.php',
  6240.                             "status" => 400,
  6241.                         ])), 400);
  6242.                     }
  6243.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  6244.                         return new Response(json_encode(([
  6245.                             'message' => 'Error, no horaire found for this audio',
  6246.                             'path' => 'src/Controller/RdvController.php',
  6247.                             "status" => 400,
  6248.                         ])), 400);
  6249.                     }
  6250.                 } else {
  6251.                     // lieu audio indie
  6252.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  6253.                         return new Response(json_encode(([
  6254.                             'message' => 'Error, no horaire found for this audio',
  6255.                             'path' => 'src/Controller/RdvController.php',
  6256.                             "status" => 400,
  6257.                         ])), 400);
  6258.                     }
  6259.                 }
  6260.             } else {
  6261.                 // regular centre
  6262.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  6263.                     return new Response(json_encode(([
  6264.                         'message' => 'Error, no horaire found for this audio',
  6265.                         'path' => 'src/Controller/RdvController.php',
  6266.                         "status" => 400,
  6267.                     ])), 400);
  6268.                 }
  6269.             }
  6270.             $rdv->setDate($date);
  6271.         }
  6272.         if (isset($data["comment"]) && $token->getIdClient()) {
  6273.             $rdv->setComment($data["comment"]);
  6274.         }
  6275.         if (isset($data["review"]) && $token->getIdClient()) {
  6276.             $rdv->setReview($data["review"]);
  6277.         }
  6278.         if (isset($data["note"])) {
  6279.             $rdv->setNote($data["note"]);
  6280.         }
  6281.         $entityManager->flush();
  6282.         $date $rdv->getDate();
  6283.         $smsDate $date->format('d-m-Y H:i');
  6284.         $oldDate $pastDate->format('d-m-Y H:i');
  6285.         $locale 'fr_FR';
  6286.         $formatter = new IntlDateFormatter(
  6287.             $locale,
  6288.             IntlDateFormatter::FULL,
  6289.             IntlDateFormatter::SHORT,
  6290.             null,
  6291.             IntlDateFormatter::GREGORIAN,
  6292.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  6293.         );
  6294.         $smsDateLongFormat $formatter->format($date);
  6295.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  6296.         $frenchDate ucfirst($frenchDate);
  6297.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  6298.         // notif client
  6299.         if ($rdv->getIdEtat()->getId() != 2) {
  6300.             $params = array(
  6301.                 "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  6302.                 "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  6303.                 "date" => $smsDateLongFormat,
  6304.                 "heure" => substr($smsDate1115),
  6305.                 "motif" => $rdv->getIdMotif()->getTitre(),
  6306.                 "centerName" => $rdv->getIdCentre()->getName(),
  6307.                 "centerAddress" => $rdv->getIdCentre()->getAddress(),
  6308.                 "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  6309.                 "audioMail" => $rdv->getIdAudio()->getMail(),
  6310.                 "centerPhone" => $rdv->getIdCentre()->getPhone(),
  6311.                 "centerCity" => $rdv->getIdCentre()->getCity(),
  6312.                 "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  6313.                 'titre' => 'Votre rendez-vous est modifié pour le',
  6314.                 'frenchDate' => $frenchDate,
  6315.             );
  6316.             $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  6317.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject184);
  6318.             if ($data["sms"]) {
  6319.                 $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.";
  6320.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  6321.             }
  6322.         }
  6323.         //     //// == suppression
  6324.         else if ($rdv->getIdEtat()->getId() == 2) {
  6325.             $params = array(
  6326.                 "date" => substr($smsDate010),
  6327.                 "lien" => "{$_ENV['BASE_client']}search",
  6328.                 "heure" => substr($smsDate1115),
  6329.                 "patientName" => $client->getLastName(),
  6330.                 'titre' => 'Votre rendez-vous est annulé :',
  6331.                 'centerName' => $rdv->getIdCentre()->getName(),
  6332.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  6333.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  6334.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  6335.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  6336.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  6337.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  6338.                 'motif' => $rdv->getIdMotif()->getTitre(),
  6339.             );
  6340.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  6341.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject188);
  6342.             if ($data["sms"]) {
  6343.                 $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  6344.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  6345.             }
  6346.         }
  6347.         //notif Audio
  6348.         if ($rdv->getIdEtat()->getId() != 2) {
  6349.             if ($data["sms"]) {
  6350.                 $params = array(
  6351.                     "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  6352.                     "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  6353.                     "date" => substr($smsDate010),
  6354.                     "frenchDate" => $frenchDate,
  6355.                     "heure" => substr($smsDate1115),
  6356.                     'motif' => $rdv->getIdMotif()->getTitre(),
  6357.                     'clientPhone' => $client->getPhone(),
  6358.                     'clientNom' => $client->getLastname(),
  6359.                     'clientPrenom' => $client->getName(),
  6360.                     'clientCivilite' => $client->getCivilite(),
  6361.                     'clientPostal' => $client->getPostal(),
  6362.                     'clientMail' => $client->getMail(),
  6363.                     'centerName' => $rdv->getIdCentre()->getName(),
  6364.                     'centerPostal' => $rdv->getIdCentre()->getPostale(),
  6365.                     'centerCity' => $rdv->getIdCentre()->getCity(),
  6366.                     'centerAddress' => $rdv->getIdCentre()->getAddress(),
  6367.                     'idPatient' => $client->getId(),
  6368.                     'proUrl' => "{$_ENV['BASE_logiciel']}",
  6369.                     'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  6370.                     'titre' => 'Votre rendez-vous est modifié pour le :'
  6371.                 );
  6372.                 $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  6373.                 $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  6374.                 if ($rdv->getIdAudio()->getModifRdvMail()) {
  6375.                     $subject "🔀 Rendez-vous My Audio modifié du " $frenchDate " à " substr($smsDate1115);
  6376.                     $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject186);
  6377.                 }
  6378.                 if ($rdv->getIdAudio()->getModifRdvSms()) {
  6379.                     $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.";
  6380.                     // $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $phoneAudio);
  6381.                 }
  6382.             }
  6383.         } else if ($rdv->getIdEtat()->getId() == 2) {
  6384.             if ($data["sms"]) {
  6385.                 $params = array(
  6386.                     "date" => substr($smsDate010),
  6387.                     "lien" => "{$_ENV['BASE_client']}search",
  6388.                     "heure" => substr($smsDate1115),
  6389.                     "patientName" => $client->getLastName(),
  6390.                     'titre' => 'Votre rendez-vous est annulé :',
  6391.                     'centerName' => $rdv->getIdCentre()->getName(),
  6392.                     'centerPostal' => $rdv->getIdCentre()->getPostale(),
  6393.                     'centerCity' => $rdv->getIdCentre()->getCity(),
  6394.                     'centerAddress' => $rdv->getIdCentre()->getAddress(),
  6395.                     'centerPhone' => $rdv->getIdCentre()->getPhone(),
  6396.                     'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  6397.                     'audioMail' => $rdv->getIdAudio()->getMail(),
  6398.                     'motif' => $rdv->getIdMotif()->getTitre(),
  6399.                 );
  6400.                 $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  6401.                 $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  6402.                 if ($rdv->getIdAudio()->getModifRdvMail()) {
  6403.                     $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  6404.                     $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject188);
  6405.                 }
  6406.                 if ($rdv->getIdAudio()->getModifRdvSms()) {
  6407.                     $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.";
  6408.                     //$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $phoneAudio);
  6409.                 }
  6410.             }
  6411.         }
  6412.         /* generate sms notif on update */
  6413.         // update sms notification     
  6414.         $rdvSms->updateRdvSms($rdv);
  6415.         // google calendar update
  6416.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  6417.             ->findBy(array('audio' => $rdv->getIdAudio()));
  6418.         $data['rdv'] = $rdv->getId();
  6419.         $data['motif_id'] = $rdv->getIdMotif();
  6420.         $data['note'] = $rdv->getNote();
  6421.         if ($rdv->getIdClient() !== null) {
  6422.             $data["client_id"] = $rdv->getIdClient()->getId();
  6423.         }
  6424.         if ($rdv->getIdClientTemp() !== null) {
  6425.             $data["client_id_temp"] = $rdv->getIdClientTemp()->getId();
  6426.         }
  6427.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  6428.             ->findBy(array('rdv' => $rdv));
  6429.         foreach ($rdvEvents as $rdvEvent) {
  6430.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  6431.             $googleCalendar->updateEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
  6432.         }
  6433.         return new Response(json_encode(([
  6434.             "id" => $rdv->getId(),
  6435.             "motif_id" => $rdv->getIdMotif()->getId(),
  6436.             "audio_id" => $rdv->getIdAudio()->getId(),
  6437.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  6438.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  6439.             "fullName" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  6440.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  6441.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  6442.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  6443.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  6444.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  6445.             "centre_id" => $rdv->getIdCentre()->getId(),
  6446.             "centerName" => $rdv->getIdCentre()->getName(),
  6447.             "etat_id" => $rdv->getIdEtat()->getId(),
  6448.             "date" => $rdv->getDate(),
  6449.             "comment" => $rdv->getComment(),
  6450.             "note" => $rdv->getNote(),
  6451.             "review" => $rdv->getReview(),
  6452.             "status" => 200,
  6453.         ])));
  6454.     }
  6455.     /**
  6456.      * @Route("/rdv/{id}/absence", name="deletetAbsenceCalendar", methods={"DELETE"})
  6457.      */
  6458.     public function deletetAbsenceCalendar(Request $requestRdv $rdvGoogleCalendarService $googleCalendar): Response
  6459.     {
  6460.         $data json_decode($request->getContent(), true);
  6461.         if (!isset($data["token"])) {
  6462.             return new Response(json_encode([
  6463.                 "message" => "Pas de token n'a été spécifié",
  6464.                 "status" => 401,
  6465.             ]), 401);
  6466.         }
  6467.         $entityManager $this->getDoctrine()->getManager();
  6468.         /** @var Token */
  6469.         $token $this->getDoctrine()
  6470.             ->getRepository(Token::class)
  6471.             ->findOneBy(['token' => $data["token"]]);
  6472.         if (!$token) {
  6473.             return new Response(json_encode([
  6474.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  6475.                 "status" => 404,
  6476.             ]), 404);
  6477.         }
  6478.         // get token age
  6479.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  6480.         // if the token if older than 7 days
  6481.         if ($dateDiff->7) {
  6482.             $entityManager->remove($token);
  6483.             $entityManager->flush();
  6484.             return $this->json([
  6485.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  6486.                 'path' => 'src/Controller/ClientController.php',
  6487.                 "status" => 401,
  6488.             ], 401);
  6489.         }
  6490.         // delete google agenda event
  6491.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  6492.             ->findBy(array('rdv' => $rdv));
  6493.         //dd($rdvEvents);
  6494.         foreach ($rdvEvents as $rdvEvent) {
  6495.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  6496.             $googleCalendar->deleteEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId());
  6497.             $entityManager->remove($rdvEvent);
  6498.             $entityManager->flush();
  6499.         }
  6500.         $entityManager->remove($rdv);
  6501.         $entityManager->flush();
  6502.         return new Response(json_encode(([
  6503.             "message" => "Absence Supprime",
  6504.             "status" => 200,
  6505.         ])));
  6506.     }
  6507.     /**
  6508.      * @Route("/rdvs/facturation/rdv", name="getMyRDV", methods={"GET"})
  6509.      */
  6510.     public function getMyRDV(Request $request): Response
  6511.     {
  6512.         /* $date = new DateTime();
  6513.         $minutes_to_add = 10;
  6514.         $date->add(new DateInterval('PT' . $minutes_to_add . 'M'));
  6515.         $date->setTimezone(new DateTimeZone('Europe/Paris'));
  6516.         $currentDate = $date->format('Y-m-d H:i:00');
  6517.         $toSend = $this->getDoctrine()->getRepository(Rdv::class)
  6518.             ->findRdvsIn10Mins($currentDate); 
  6519.         */
  6520.     }
  6521.     /**
  6522.      * @Route("/rdvs/facturation/lead", name="getMyLead", methods={"GET"})
  6523.      */
  6524.     public function getMyLead(Request $request): Response {}
  6525.     /**
  6526.      * @Route("/rdvs/total-count", name="getRdvCount", methods={"GET"})
  6527.      */
  6528.     public function getRdvCount(Request $request): Response
  6529.     {
  6530.         $rdvs $this->getDoctrine()->getRepository(Rdv::class)->findAll();
  6531.         return new Response(count($rdvs));
  6532.     }
  6533.     /**
  6534.      * @Route("/admin/update-relance/{id}", name="admin_update_relance", methods={"POST"})
  6535.      */
  6536.     public function updateRelance(Request $requestLeadRdv $leadEntityManagerInterface $em): JsonResponse
  6537.     {
  6538.         $data json_decode($request->getContent(), true);
  6539.         $relanceCount $data['relanceCount'] ?? null;
  6540.         if ($relanceCount !== null) {
  6541.             $lead->setRelanceCallCount((int)$relanceCount);
  6542.             $em->flush();
  6543.             return new JsonResponse(['success' => true]);
  6544.         }
  6545.         return new JsonResponse(['success' => false], 400);
  6546.     }
  6547.     /**
  6548.      * @Route("/rdv/lead", name="postLeadRdv", methods={"POST"})
  6549.      */
  6550.     public function postLeadRdv(Request $requestEntityManagerInterface $entityManagerPublicFunction $publicFunctionGoogleCalendarService $googleCalendar): Response
  6551.     {
  6552.         $data json_decode($request->getContent(), true);
  6553.         $today = new DateTime();
  6554.         try {
  6555.             $client null;
  6556.             // Gestion du client via token ou création
  6557.             if (!empty($data['clientToken'])) {
  6558.                 $token $entityManager->getRepository(Token::class)->findOneBy(['token' => $data['clientToken']]);
  6559.                 $client $token $token->getIdClient() : null;
  6560.             } elseif (!empty($data['client'])) {
  6561.                 $clientData $this->createOrGetClient($data['client']);
  6562.                 $client $entityManager->getRepository(Client::class)->find($clientData['id']);
  6563.             }
  6564.             if (!$client) {
  6565.                 return $this->json(["status" => 400"message" => "Client non trouvé ou invalide"], 400);
  6566.             }
  6567.             // Création du rendez-vous LeadRdv
  6568.             $rdvLead = new LeadRdv();
  6569.             $rdvLead->setClient($client);
  6570.             if (isset($data['titleLead'])) {
  6571.                 $rdvLead->setTitleLead($data['titleLead']);
  6572.             }
  6573.             if (isset($data['rangeAge'])) {
  6574.                 $rdvLead->setRangeAge($data['rangeAge']);
  6575.             }
  6576.             if (isset($data['situations'])) {
  6577.                 $rdvLead->setSituationsGene($data['situations']);
  6578.             }
  6579.             if (isset($data['equipe'])) {
  6580.                 $rdvLead->setEquipeAppareil($data['equipe']);
  6581.             }
  6582.             if (isset($data['durationEquipe'])) {
  6583.                 $rdvLead->setDurationEquipeAppareil($data['durationEquipe']);
  6584.             }
  6585.             if (isset($data['bilanAuditif'])) {
  6586.                 $rdvLead->setBilanAuditif($data['bilanAuditif']);
  6587.             }
  6588.             if (isset($data['ordonance'])) {
  6589.                 $rdvLead->setOrdonance($data['ordonance']);
  6590.             }
  6591.             if (isset($data['dateOrdonance'])) {
  6592.                 $rdvLead->setDateOrdonance($data['dateOrdonance']);
  6593.             }
  6594.             if (isset($data['canMove'])) {
  6595.                 $rdvLead->setCanMove($data['canMove']);
  6596.             }
  6597.             if (isset($data['traffic_source'])) {
  6598.                 $rdvLead->setTrafficSource($data['traffic_source']);
  6599.             }
  6600.             if (isset($data['article_name'])) {
  6601.                 $rdvLead->setTrafficLpVersion($data['article_name']);
  6602.             }
  6603.             if (isset($data['lp_version'])) {
  6604.                 $rdvLead->setTrafficArticleName($data['lp_version']);
  6605.             }
  6606.             if (isset($data['isNewLp'])) {
  6607.                 $rdvLead->setIsNewLp($data['isNewLp']);
  6608.                 $leadStatus $entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'demande_contact']);
  6609.                 if ($leadStatus) {
  6610.                     $rdvLead->setLeadStatus($leadStatus);
  6611.                 }
  6612.             }
  6613.             $rdvLead->setDate($today);
  6614.             if (!empty($data['audio'])) {
  6615.                 $audio $entityManager->getRepository(Audio::class)->find($data['audio']);
  6616.                 if ($audio) {
  6617.                     $rdvLead->setAudio($audio);
  6618.                 }
  6619.             }
  6620.             if ($client->getPostal()) {
  6621.                 $centerCount $this->getMatchingCentresCount($client->getPostal());
  6622.                 $rdvLead->setCentersCount($centerCount);
  6623.                 if ($centerCount == 0) {
  6624.                     $leadStatus $entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'hors_zone']);
  6625.                     if ($leadStatus) {
  6626.                         $rdvLead->setLeadStatus($leadStatus);
  6627.                     }
  6628.                 }
  6629.             }
  6630.             // Création du Token
  6631.             $tokenString $publicFunction->generateRandomString(30);
  6632.             $token = (new Token())
  6633.                 ->setCreationDate(new DateTime())
  6634.                 ->setToken($tokenString)
  6635.                 ->setIdClient($client);
  6636.             $entityManager->persist($rdvLead);
  6637.             $entityManager->persist($token);
  6638.             $entityManager->flush();
  6639.             return $this->json([
  6640.                 "id" => $client->getId(),
  6641.                 "idRdvLead" => $rdvLead->getId(),
  6642.                 "name" => $client->getName(),
  6643.                 "lastname" => $client->getLastname(),
  6644.                 "token" => $tokenString,
  6645.                 "code" => $clientData['password'],
  6646.                 "postalCode" => $client->getPostal() ?? null,
  6647.                 "status" => 200,
  6648.             ]);
  6649.         } catch (\Exception $e) {
  6650.             return $this->json(["status" => 500"message" => $e->getMessage()], 500);
  6651.         }
  6652.     }
  6653.     /**
  6654.      * @Route("/testGenerateVoice", name="testGenerateVoice", methods={"GET"})
  6655.      */
  6656.     public function testGenerateVoice(AppointmentCallService $service): Response
  6657.     {
  6658.         // TEST LOCAL$rdv = $this->entityManager->getRepository(Rdv::class)->find(6653);
  6659.         $rdv $this->entityManager->getRepository(Rdv::class)->find(2306);
  6660.         $lead $this->entityManager->getRepository(LeadRdv::class)->find(496);
  6661.         // $service->handleCallCenterAfterRdv(
  6662.         //     $rdv
  6663.         // );
  6664.         // $service->handleReminderCallToPatient(
  6665.         //     $rdv
  6666.         // );
  6667.         $service->handleEquipmentStatusCall($rdv);
  6668.         // $service->handleReminderCallToPatientOneHourBefore(
  6669.         //     $rdv
  6670.         // );
  6671.         // $service->handleCallToPatientAfterRdv(
  6672.         //     $rdv
  6673.         // );
  6674.         // $service->handleFollowupCall15Days($rdv);
  6675.         // $service->handleNewLeadCall($lead, "+33743393532");
  6676.         // $service->handleFollowupCall31Days($rdv);
  6677.         return new Response(json_encode([
  6678.             "status" => 200,
  6679.         ]), 200, ['Content-Type' => 'application/json']);
  6680.     }
  6681.     /**
  6682.      * @Route("/testSynthflow", name="testSynthflow", methods={"POST"})
  6683.      */
  6684.     public function testSynthflow(SynthflowService $service): Response
  6685.     {
  6686.         // TEST LOCAL
  6687.         $lead $this->entityManager->getRepository(LeadRdv::class)->find(496);
  6688.         $service->initiateCall($lead);
  6689.         return new Response(json_encode([
  6690.             "status" => 200,
  6691.         ]), 200, ['Content-Type' => 'application/json']);
  6692.     }
  6693.     /**
  6694.      * Private method to create a new client or get existing one by phone
  6695.      */
  6696.     private function createOrGetClient(array $data): array
  6697.     {
  6698.         $clientRepository $this->entityManager->getRepository(Client::class);
  6699.         // check sur le mail et phone
  6700.         $existingClient $clientRepository->findOneBy(['mail' => $data['email']]);
  6701.         if ($existingClient) {
  6702.             if ($existingClient->getPostal() !== $data['postalCode']) {
  6703.                 $existingClient->setPostal($data['postalCode']);
  6704.                 $this->entityManager->persist($existingClient);
  6705.                 $this->entityManager->flush();
  6706.             }
  6707.             return ['id' => $existingClient->getId(), 'password' => 'Votre mot de passe'];
  6708.         }
  6709.         $randomPassword $this->generateRandomPassword(12);
  6710.         $client = new Client();
  6711.         $client->setLastname($data['lastname']);
  6712.         $client->setBirthdate(null);
  6713.         $client->setName($data['firstname']);
  6714.         $client->setPhone($data['phone']);
  6715.         $client->setMail($data['email']);
  6716.         $client->setSignupDate(new \DateTime());
  6717.         $client->setPassword(password_hash($randomPasswordPASSWORD_DEFAULT));
  6718.         $client->setPostal($data['postalCode']);
  6719.         $client->setAddress($data['address'] ?? null);
  6720.         $client->setCity($data['city'] ?? null);
  6721.         $client->setDesactivate(false);
  6722.         if (isset($data['civilite'])) {
  6723.             $civilite = ($data['civilite'] === 'Homme') ? 'Monsieur' 'Madame';
  6724.             $client->setCivilite($civilite);
  6725.         }
  6726.         $this->entityManager->persist($client);
  6727.         $this->entityManager->flush();
  6728.         return ['id' => $client->getId(), 'password' => $randomPassword];
  6729.     }
  6730.     private function generateRandomPassword($length 10): string
  6731.     {
  6732.         return bin2hex(random_bytes($length 2));
  6733.     }
  6734.     private function getMatchingCentresCount($clientPostal): int
  6735.     {
  6736.         // Récupérer les coordonnées GPS du code postal du client
  6737.         $clientCoordinates $this->entityManager
  6738.             ->getRepository(RegionDepartment::class)
  6739.             ->findOneBy(['codePostal' => $clientPostal]);
  6740.         $clientLat $clientCoordinates $clientCoordinates->getLatitude() : null;
  6741.         $clientLon $clientCoordinates $clientCoordinates->getLongitude() : null;
  6742.         $centres $this->entityManager->getRepository(Centre::class)->findAll();
  6743.         $count 0;
  6744.         foreach ($centres as $centre) {
  6745.             if ($centre->getZoneKm()) {
  6746.                 $latitude $centre->getLatitude();
  6747.                 $longitude $centre->getLongitude();
  6748.                 $radius $centre->getZoneKm();
  6749.                 $postals $this->entityManager->getRepository(RegionDepartment::class)->findPostalsWithinRadius($latitude$longitude$radius);
  6750.                 $postalCodes array_values(array_unique(array_column($postals'code_postal')));
  6751.                 if (in_array($clientPostal$postalCodes)) {
  6752.                     $count++;
  6753.                 }
  6754.             }
  6755.         }
  6756.         return $count;
  6757.     }
  6758.     /**
  6759.      * @Route("/rdv/send-map", name="getRdvMap", methods={"POST"})
  6760.      */
  6761.     public function sendEmailWithMap(Request $requestPublicFunction $publicFunction): Response
  6762.     {
  6763.         $data json_decode($request->getContent(), true);
  6764.         $mail "";
  6765.         $name "";
  6766.         $centre "";
  6767.         if (isset($data['clientToken'])) {
  6768.             $token $this->getDoctrine()->getRepository(Token::class)->findOneBy(['token' => $data['clientToken']]);
  6769.             $client $token->getIdClient();
  6770.             $mail $client->getMail();
  6771.             $name $client->getLastname() . " " $client->getName();
  6772.             $centre $this->getDoctrine()->getRepository(Centre::class)->findOneBy(['id' => $data['centre']['id']]);
  6773.         } else {
  6774.             $mail $data['email'];
  6775.             $name $data['name'];
  6776.         }
  6777.         $locale 'fr_FR';
  6778.         $dateTime DateTime::createFromFormat('d/m/Y H:i'$data['date']);
  6779.         if ($dateTime) {
  6780.             $fmt = new IntlDateFormatter($localeIntlDateFormatter::FULLIntlDateFormatter::NONE);
  6781.             $fmt->setPattern("EEEE dd MMMM");
  6782.             $formattedDate ucfirst($fmt->format($dateTime));
  6783.         } else {
  6784.             $formattedDate "Date invalide";
  6785.         }
  6786.         $params = [
  6787.             'date' => $data['date'],
  6788.             'time' => $data['time'],
  6789.             'frenchDate' => $formattedDate,
  6790.             'clientAddress' => $data['address'],
  6791.             'centerName' => $centre->getName(),
  6792.             'centerAddress' => $centre->getAddress(),
  6793.             'centerPostal' => $centre->getPostale(),
  6794.             'centerCity' => $centre->getCity(),
  6795.             'start' => $data['start'],
  6796.             'end' => $data['end'],
  6797.             'urlApi' => "{$_ENV['BASE_client']}",
  6798.         ];
  6799.         $publicFunction->sendEmail($params$mail$name"Votre Rendez-vous My Audio"198);
  6800.         return new Response(json_encode([
  6801.             "status" => 200,
  6802.             "params" => $params,
  6803.         ]), 200, ['Content-Type' => 'application/json']);
  6804.     }
  6805.     /**
  6806.      * @Route("/rdv/cantmove", name="notifCantMove", methods={"POST"})
  6807.      */
  6808.     public function notifCantMove(Request $requestPublicFunction $publicFunction): Response
  6809.     {
  6810.         $data json_decode($request->getContent(), true);
  6811.         $email "lead.myaudio@gmail.com";
  6812.         $centre "";
  6813.         $type "My Audio";
  6814.         $details "";
  6815.         $picto "❌";
  6816.         $ordo "sans ordo";
  6817.         $subject "";
  6818.         if (isset($data['ordonance'])) {
  6819.             if ($data["ordonance"] == "oui") {
  6820.                 $ordo "avec ordo";
  6821.             }
  6822.         } else {
  6823.             $ordo "";
  6824.         }
  6825.         if (isset($data['centre'])) {
  6826.             $centre $data['centre'];
  6827.             $subject $picto " Lead - demande de contact ne pouvant pas se déplacer " $data['postal'] . " " $ordo;
  6828.         } else {
  6829.             $centre "";
  6830.             $type "Hors Zone";
  6831.             $details "Pas de centre dans la zone";
  6832.             $subject $picto " Lead Hors Zone " $data['postal'] . " " $ordo " ne pouvant pas se déplacer";
  6833.         }
  6834.         $responses = [
  6835.             'rangeAge' => isset($data['rangeAge']) ? $data['rangeAge'] : null,
  6836.             'situations' => isset($data['situations']) ? $data['situations'] : null,
  6837.             'equipeAppareil' => isset($data['equipe']) ? $data['equipe'] : null,
  6838.             'durationEquipe' => isset($data['durationEquipe']) ? $data['durationEquipe'] : null,
  6839.             'bilanAuditif' => isset($data['bilanAuditif']) ? $data['bilanAuditif'] : null,
  6840.             'ordonance' => isset($data['ordonance']) ? $data['ordonance'] : null,
  6841.             'dateOrdonance' => isset($data['dateOrdonance']) ? $data['dateOrdonance'] : null,
  6842.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  6843.         ];
  6844.         $department $this->getDepartmentFromPostalCode($data['address']);
  6845.         $data['departmentCode'] = $department['departmentCode'];
  6846.         $data['departmentName'] = $department['departmentName'];
  6847.         $data['regionName'] = $department['regionName'];
  6848.         $data['city'] = $department['city'];
  6849.         $params = [
  6850.             'date' => $data['date'],
  6851.             'time' => $data['time'],
  6852.             'address' => $data['address'],
  6853.             'centre' => $centre,
  6854.             'type' => $type,
  6855.             'details' => $details,
  6856.             'responses' => $responses,
  6857.             'name' => $data['name'],
  6858.             'civilite' => $data['civilite'],
  6859.             'nom' => $data['firstname'],
  6860.             'prenom' => $data['lastname'],
  6861.             'codePostal' => $data['address'],
  6862.             'telephone' => $data['phone'],
  6863.             'email' => $data['email'],
  6864.             'departement' => $data['departmentName'],
  6865.             'ville' => $data['city'],
  6866.             'region' => $data['regionName'],
  6867.             'trangeAge' => isset($data['rangAge']) ? $data['rangAge'] : null,
  6868.             'situationVecu' => isset($data['situations']) ? implode(', '$data['situations']) : null,
  6869.             'dejaEquipe' => isset($data['equipeAppareil']) ? $data['equipeAppareil'] : null,
  6870.             'trafficSource' => isset($data['traffic_source']) ? $data['traffic_source'] : null,
  6871.             'articleName' => isset($data['article_name']) ? $data['article_name'] : null,
  6872.             'lpVersion' => isset($data['lp_version']) ? $data['lp_version'] : null,
  6873.         ];
  6874.         $publicFunction->sendEmail($params$email$data['name'], $subject208);
  6875.         return new Response(json_encode([
  6876.             "status" => 200,
  6877.         ]), 200, ['Content-Type' => 'application/json']);
  6878.     }
  6879.     /**
  6880.      * @Route("/rdv/cantmove/v2", name="notifCantMoveV2", methods={"POST"})
  6881.      */
  6882.     public function notifCantMoveV2(Request $requestPublicFunction $publicFunction): Response
  6883.     {
  6884.         $data json_decode($request->getContent(), true);
  6885.         $email "lead.myaudio@gmail.com";
  6886.         $centre "";
  6887.         $type "My Audio";
  6888.         $details "";
  6889.         $picto "❌";
  6890.         $subject "";
  6891.         $audio "";
  6892.         $subject $picto " Lead ne pouvant pas se déplacer";
  6893.         $department $this->getDepartmentFromPostalCode($data['address']);
  6894.         $data['departmentCode'] = $department['departmentCode'];
  6895.         $data['departmentName'] = $department['departmentName'];
  6896.         $data['regionName'] = $department['regionName'];
  6897.         $data['city'] = $department['city'];
  6898.         $password "";
  6899.         $params = [
  6900.             'name' => $data['name'],
  6901.             'civilite' => $data['civilite'],
  6902.             'nom' => $data['firstname'],
  6903.             'prenom' => $data['lastname'],
  6904.             'codePostal' => $data['address'],
  6905.             'telephone' => $data['phone'],
  6906.             'email' => $data['email'],
  6907.             'password' => $data['clientSecretCookie'],
  6908.             'trancheAge' => isset($data['rangAge']) ? $data['rangAge'] : null,
  6909.             'situationVecu' => isset($data['situations']) ? implode(', '$data['situations']) : null,
  6910.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  6911.             'trafficSource' => isset($data['traffic_source']) ? $data['traffic_source'] : null,
  6912.             'articleName' => isset($data['article_name']) ? $data['article_name'] : null,
  6913.             'lpVersion' => isset($data['lp_version']) ? $data['lp_version'] : null,
  6914.             'urlLogin' => "{$_ENV['BASE_client']}login"
  6915.         ];
  6916.         // Send email to MyAudio
  6917.         $publicFunction->sendEmail($params$email$data['name'], $subject220);
  6918.         $publicFunction->sendEmail($params'contact@myaudio.fr'$data['name'], $subject220);
  6919.         // Send email to patient
  6920.         $params = [
  6921.             'clientEmail' => $data['email'],
  6922.             'clientPassword' => $data['clientSecretCookie'],
  6923.             'rdv' => "https://www.myaudio.fr/search",
  6924.             'urlLogin' => "{$_ENV['BASE_client']}login"
  6925.         ];
  6926.         $publicFunction->sendEmail($params$data['email'], $data['name'], 'Rendez-vous My Audio - En cours de traitement'219);
  6927.         $rdvLead $this->entityManager->getRepository(LeadRdv::class)->find($data['clientRdvLp']);
  6928.         if ($rdvLead) {
  6929.             $leadStatus $this->entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'cant_move']);
  6930.             if ($leadStatus) {
  6931.                 $rdvLead->setLeadStatus($leadStatus);
  6932.                 $this->entityManager->flush();
  6933.             }
  6934.         }
  6935.         return new Response(json_encode([
  6936.             "status" => 200,
  6937.         ]), 200, ['Content-Type' => 'application/json']);
  6938.     }
  6939.     /**
  6940.      * @Route("/rdv/notiflead", name="notifLead", methods={"POST"})
  6941.      */
  6942.     public function notifLeadRdv(Request $requestPublicFunction $publicFunction): Response
  6943.     {
  6944.         $data json_decode($request->getContent(), true);
  6945.         $email "lead.myaudio@gmail.com";
  6946.         $centre "";
  6947.         $type "My Audio";
  6948.         $details "";
  6949.         $picto "❌";
  6950.         $ordo "sans ordo";
  6951.         $subject "";
  6952.         $name "";
  6953.         $postal "";
  6954.         $emailPatient "";
  6955.         if (isset($data['clientToken']) && !empty($data['clientToken'])) {
  6956.             $token $this->getDoctrine()->getRepository(Token::class)->findOneBy(['token' => $data['clientToken']]);
  6957.             $client $token->getIdClient();
  6958.             $name $client->getLastname() . " " $client->getName();
  6959.             $postal $client->getPostal();
  6960.             $emailPatient $client->getMail();
  6961.         } else {
  6962.             if (isset($data['postal'])) {
  6963.                 $postal $data['postal'];
  6964.             }
  6965.             if (isset($data['name'])) {
  6966.                 $name $data['name'];
  6967.             }
  6968.             if (isset($data['email'])) {
  6969.                 $email $data['email'];
  6970.             }
  6971.             if (isset($data['email'])) {
  6972.                 $emailPatient $data['email'];
  6973.             }
  6974.         }
  6975.         if (isset($data["ordonance"])) {
  6976.             if ($data["ordonance"] == "oui") {
  6977.                 $ordo "avec ordo";
  6978.             }
  6979.         }
  6980.         if (isset($data['centre'])) {
  6981.             $centre $data['centre'];
  6982.             $picto "✅";
  6983.             $subject $picto " Lead booké " $postal " " $ordo;
  6984.         } else {
  6985.             $centre "";
  6986.             $type "Hors Zone";
  6987.             $details "Pas de centre dans la zone";
  6988.             $subject $picto " Lead Hors Zone " $postal " " $ordo;
  6989.         }
  6990.         $responses = [
  6991.             'rangeAge' => isset($data['rangeAge']) ? $data['rangeAge'] : null,
  6992.             'situations' => isset($data['situations']) ? $data['situations'] : null,
  6993.             'equipeAppareil' => isset($data['equipe']) ? $data['equipe'] : null,
  6994.             'durationEquipe' => isset($data['durationEquipe']) ? $data['durationEquipe'] : null,
  6995.             'bilanAuditif' => isset($data['bilanAuditif']) ? $data['bilanAuditif'] : null,
  6996.             'ordonance' => isset($data['ordonance']) ? $data['ordonance'] : null,
  6997.             'dateOrdonance' => isset($data['dateOrdonance']) ? $data['dateOrdonance'] : null,
  6998.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  6999.         ];
  7000.         $params = [
  7001.             'date' => $data['date'],
  7002.             'time' => $data['time'],
  7003.             'address' => $data['address'],
  7004.             'centre' => $centre,
  7005.             'type' => $type,
  7006.             'details' => $details,
  7007.             'responses' => $responses,
  7008.             'name' => $name,
  7009.             'email' => $emailPatient,
  7010.         ];
  7011.         $publicFunction->sendEmail($params$email$name$subject180);
  7012.         return new Response(json_encode([
  7013.             "status" => 200,
  7014.             "params" => $params,
  7015.             "responses" => $responses
  7016.         ]), 200, ['Content-Type' => 'application/json']);
  7017.     }
  7018.     /**
  7019.      *  Met à jour l'état d'un rendez-vous.
  7020.      *
  7021.      * Cette fonction permet de modifier l'état d'un rendez-vous en fonction des données envoyées
  7022.      * via une requête PUT. Elle effectue plusieurs vérifications, notamment :
  7023.      * - La présence et la validité du token d'authentification.
  7024.      * - L'existence du rendez-vous et du nouvel état.
  7025.      * - L'expiration du token (plus de 7 jours).
  7026.      * 
  7027.      * Si le rendez-vous est marqué comme "Absence injustifiée" (état ID 3), un email et un SMS sont envoyés
  7028.      * au client et à l'équipe MyAudio pour les informer.
  7029.      * 
  7030.      * @Route("api/save-etat-rdv", name="saveEtatRdv", methods={"PUT"})
  7031.      */
  7032.     public function saveEtatRdv(Request $requestPublicFunction $publicFunction): Response
  7033.     {
  7034.         $entityManager $this->getDoctrine()->getManager();
  7035.         $data json_decode($request->getContent(), true);
  7036.         if (!$data['token']) {
  7037.             return new Response(json_encode([
  7038.                 "message" => "Pas de token n'a été spécifié",
  7039.                 "status" => 401,
  7040.             ]), 401);
  7041.         }
  7042.         /** @var Token */
  7043.         $token $this->getDoctrine()
  7044.             ->getRepository(Token::class)
  7045.             ->findOneBy(['token' => $data['token'], 'id_audio' => $data['audio']]);
  7046.         if (!$token) {
  7047.             return new Response(json_encode([
  7048.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  7049.                 "status" => 404,
  7050.             ]), 404);
  7051.         }
  7052.         // get token age
  7053.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  7054.         // if the token if older than 7 days
  7055.         if ($dateDiff->7) {
  7056.             $entityManager->remove($token);
  7057.             $entityManager->flush();
  7058.             return $this->json([
  7059.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  7060.                 'path' => 'src/Controller/ClientController.php',
  7061.                 "status" => 401,
  7062.             ], 401);
  7063.         }
  7064.         $rdv $this->getDoctrine()->getRepository(Rdv::class)->find($data['rdv']);
  7065.         if (!$rdv) {
  7066.             return new Response(json_encode([
  7067.                 "message" => "Rdv not found.",
  7068.                 "status" => 404,
  7069.             ]), 404);
  7070.         }
  7071.         $rdvEtat $this->getDoctrine()
  7072.             ->getRepository(EtatRdv::class)
  7073.             ->find($data['etat']);
  7074.         if (!$rdvEtat) {
  7075.             return new Response(json_encode([
  7076.                 "message" => "Rdv etat not found.",
  7077.                 "status" => 404,
  7078.             ]), 404);
  7079.         }
  7080.         $rdv->setIdEtat($rdvEtat);
  7081.         $entityManager->flush();
  7082.         $encodedNomDuCentre rawurlencode($rdv->getIdCentre()->getName());
  7083.         $urlApi "audioprothesiste/{$rdv->getIdCentre()->getCity()}/{$rdv->getIdCentre()->getPostale()}/{$encodedNomDuCentre}/prise-de-rdvaudioprothesiste-rapide/{$rdv->getIdCentre()->getId()}";
  7084.         if ($rdvEtat->getId() == 3) {
  7085.             // Send email to client
  7086.             $date $rdv->getDate();
  7087.             $smsDate $date->format('d-m-Y H:i');
  7088.             $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  7089.             $params = array(
  7090.                 "date" => substr($smsDate010),
  7091.                 "lien" => "{$_ENV['BASE_client']}$urlApi,
  7092.                 "heure" => substr($smsDate1115),
  7093.                 'centerName' => $rdv->getIdCentre()->getName() ?? '',
  7094.                 'centerPostal' => $rdv->getIdCentre()->getPostale() ?? '',
  7095.                 'centerCity' => $rdv->getIdCentre()->getCity() ?? '',
  7096.                 'centerAddress' => $rdv->getIdCentre()->getAddress() ?? '',
  7097.                 'centerPhone' => $rdv->getIdCentre()->getPhone() ?? '',
  7098.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName() ?? '',
  7099.                 'audioMail' => $rdv->getIdAudio()->getMail() ?? '',
  7100.             );
  7101.             $subject "Vous avez manqué votre rendez-vous MyAudio avec " $rdv->getIdCentre()->getName();
  7102.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject214);
  7103.             // Send sms to client
  7104.             $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();
  7105.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  7106.             // Send email to MyAudio
  7107.             $date $rdv->getDate();
  7108.             $smsDate $date->format('d-m-Y H:i');
  7109.             $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  7110.             $params = array(
  7111.                 "date" => substr($smsDate010),
  7112.                 "lien" => "{$_ENV['BASE_client']}search",
  7113.                 "heure" => substr($smsDate1115),
  7114.                 'centerName' => $rdv->getIdCentre()->getName() ?? '',
  7115.                 'centerPostal' => $rdv->getIdCentre()->getPostale() ?? '',
  7116.                 'centerCity' => $rdv->getIdCentre()->getCity() ?? '',
  7117.                 'centerAddress' => $rdv->getIdCentre()->getAddress() ?? '',
  7118.                 'centerPhone' => $rdv->getIdCentre()->getPhone() ?? '',
  7119.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName() ?? '',
  7120.                 'audioMail' => $rdv->getIdAudio()->getMail() ?? '',
  7121.                 'clientName' => $client->getName() . ' ' $client->getLastName() ?? '',
  7122.                 'clientMail' => $client->getMail() ?? '',
  7123.                 'clientPhone' => $client->getPhone() ?? '',
  7124.             );
  7125.             $subject "Le patient " $client->getName() . ' ' $client->getLastName() . " a manqué son rendez-vous MyAudio avec le centre " $rdv->getIdCentre()->getName();
  7126.             $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$client->getName() . ' ' $client->getLastName(), $subject215);
  7127.         }
  7128.         return new Response(json_encode([
  7129.             "message" => "rdvEtat has been successfully updated",
  7130.             "status" => 200,
  7131.         ]));
  7132.     }
  7133.     /**
  7134.      * 
  7135.      * @Route("api/send-email/clientnotcompletebook", name="askToContact", methods={"POST"})
  7136.      */
  7137.     public function askToContact(Request $requestPublicFunction $publicFunction): Response
  7138.     {
  7139.         $data json_decode($request->getContent(), true);
  7140.         $staticToken "3f3a8b74f3e5b2d0c4917f5f9a7c07efb1a0f1e5e8c907ec9c4e9df129e3125e9";
  7141.         $token $data['token'] ?? null;
  7142.         if ($token !== $staticToken) {
  7143.             return new JsonResponse(
  7144.                 [
  7145.                     'status' => 'error',
  7146.                     'code' => 'unauthorized',
  7147.                     'message' => 'Unauthorized access.'
  7148.                 ],
  7149.                 JsonResponse::HTTP_UNAUTHORIZED
  7150.             );
  7151.         }
  7152.         $params = [
  7153.             'clientCivilite' => isset($data['civilite']) ? $data['civilite'] : 'Pas indiqué',
  7154.             'clientNom' => isset($data['firstname']) ? $data['firstname'] : null,
  7155.             'clientPrenom' => isset($data['lastname']) ? $data['lastname'] : null,
  7156.             'clientPostal' => isset($data['postalCode']) ? $data['postalCode'] : null,
  7157.             'clientPhone' => isset($data['phone']) ? $data['phone'] : null,
  7158.             'clientMail' => isset($data['email']) ? $data['email'] : null,
  7159.             'password' => isset($data['clientSecretCookie']) ? $data['clientSecretCookie'] : null,
  7160.             'rangeAge' => isset($data['trancheAge']) ? $data['trancheAge'] : null,
  7161.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  7162.             'situations' => isset($data['situations']) ? implode(', '$data['situations']) : null,
  7163.             'trafficSource' => isset($data['traffic_source']) ? $data['traffic_source'] : null,
  7164.             'articleName' => isset($data['article_name']) ? $data['article_name'] : null,
  7165.             'lpVersion' => isset($data['lp_version']) ? $data['lp_version'] : null,
  7166.         ];
  7167.         $templateEmailMyAudio 223;
  7168.         if (!empty($data['centre'])) {
  7169.             $centre $data['centre'];
  7170.             $audio $centre['audio'][0];
  7171.             $params['centerName'] = $centre['name'] ?? null;
  7172.             $params['centerPostal'] = $centre['postale'] ?? null;
  7173.             $params['centerCity'] = $centre['city'] ?? null;
  7174.             $params['centerAddress'] = $centre['address'] ?? null;
  7175.             $params['centerPhone'] = $centre['phone'] ?? null;
  7176.             $params['audioproName'] = $audio['civilite'] . ' ' $audio['lastname'] . ' ' $audio['name'] ?? null;
  7177.             $templateEmailMyAudio 222;
  7178.         }
  7179.         // Email to My Audio
  7180.         $email "lead.myaudio@gmail.com";
  7181.         $subject "Demande de contact -  Nouveau Lead À Contacter Hors Zone";
  7182.         $publicFunction->sendEmail($params$email$data['name'], $subject$templateEmailMyAudio);
  7183.         $publicFunction->sendEmail($params'contact@myaudio.fr'$data['name'], $subject$templateEmailMyAudio);
  7184.         $coordinates $this->getCoordinatesFromPostalCode($data['postalCode']);
  7185.         $latitude $coordinates['latitude'];
  7186.         $longitude $coordinates['longitude'];
  7187.         $params = [
  7188.             'email' => isset($data['email']) ? $data['email'] : null,
  7189.             'password' => isset($data['clientSecretCookie']) ? $data['clientSecretCookie'] : null,
  7190.             "lienRdv" => "{$_ENV['BASE_client']}search?latitude={$latitude}&longitude={$longitude}&ville={$data['postalCode']}",
  7191.         ];
  7192.         // Email to Client
  7193.         $subject "My Audio - Confirmation de demande de contact";
  7194.         $publicFunction->sendEmail($params$data['email'], $data['name'], $subject221);
  7195.         $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";
  7196.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$data['phone']);
  7197.         if (isset($data['clientRdvLp'])) {
  7198.             $rdvLead $this->entityManager->getRepository(LeadRdv::class)->find($data['clientRdvLp']);
  7199.             if ($rdvLead) {
  7200.                 $rdvLead->setSendAskToContact(1);
  7201.                 $rdvLead->setCountAskToContact(($rdvLead->getCountAskToContact() ?? 0) + 1);
  7202.                 $this->entityManager->flush();
  7203.                 $this->sendWhatsApp($data$rdvLead);
  7204.             }
  7205.         }
  7206.         return new Response(json_encode([
  7207.             "message" => "Email ask for contact send with success",
  7208.             "status" => 200,
  7209.         ]));
  7210.     }
  7211.     private function sendWhatsApp($data$lead): void
  7212.     {
  7213.         $adminUrl $this->adminUrlGenerator
  7214.             ->setDashboard(DashboardController::class)
  7215.             ->setController(LeadRdvCrudController::class)
  7216.             ->setAction('detail')
  7217.             ->setEntityId($lead->getId())
  7218.             ->generateUrl();
  7219.         $relativeUrl parse_url($adminUrlPHP_URL_PATH) . '?' parse_url($adminUrlPHP_URL_QUERY);
  7220.         // Supprimer le slash en trop s’il y en a un au début
  7221.         $relativeUrl ltrim($relativeUrl'/');
  7222.         // 🧑‍🤝‍🧑 Tableau des destinataires
  7223.         $destinataires = [
  7224.             '33611879183'// Numéro 1
  7225.             '33667597626'// Numéro 2
  7226.             '447884128220'// Numéro 3
  7227.         ];
  7228.         foreach ($destinataires as $numero) {
  7229.             $this->whatsapp->sendTemplateMessage(
  7230.                 $numero,  // Numéro de téléphone du destinataire
  7231.                 'lead_notif_myaudio',  // Nom du template WhatsApp
  7232.                 [
  7233.                     'body' => [
  7234.                         ['parameter_name' => 'nom_client''text' => $data['firstname'] . ' ' $data['lastname']],  // {{nom_client}}
  7235.                         ['parameter_name' => 'email_client''text' => $data['email'] ?? ' '],  // {{email_client}}
  7236.                         ['parameter_name' => 'telephone_client''text' => $data['phone'] ?? ' '],  // {{telephone_client}}
  7237.                         ['parameter_name' => 'date_lead''text' => $lead->getDate()->format('d/m/Y H:i')],  // {{date_lead}}
  7238.                         ['parameter_name' => 'code_postal''text' => $data['postalCode'] ?? ' '],  // {{code_postal}}
  7239.                         ['parameter_name' => 'nombre_centres''text' => $lead->getCentersCount() ?? '0'],  // {{nombre_centres}}
  7240.                     ],
  7241.                     'button' => $relativeUrl,  // <--- seulement le chemin dynamique
  7242.                 ]
  7243.             );
  7244.         }
  7245.     }
  7246.     /**
  7247.      * Get coordinates from the postal code using the database.
  7248.      */
  7249.     private function getCoordinatesFromPostalCode(string $postalCode): array
  7250.     {
  7251.         $region $this->entityManager
  7252.             ->getRepository(RegionDepartment::class)
  7253.             ->findOneBy(['codePostal' => $postalCode]);
  7254.         if ($region) {
  7255.             return [
  7256.                 'latitude' => $region->getLatitude(),
  7257.                 'longitude' => $region->getLongitude(),
  7258.             ];
  7259.         }
  7260.         return [
  7261.             'latitude' => null,
  7262.             'longitude' => null,
  7263.         ];
  7264.     }
  7265.     /**
  7266.      * Get the department code from the code postal
  7267.      */
  7268.     private function getDepartmentFromPostalCode(string $postalCode): ?array
  7269.     {
  7270.         $region $this->entityManager
  7271.             ->getRepository(RegionDepartment::class)
  7272.             ->findOneBy(['codePostal' => $postalCode]);
  7273.         if ($region) {
  7274.             return [
  7275.                 'departmentCode' => $region->getCodeDepartement(),
  7276.                 'departmentName' => $region->getNomDepartement(),
  7277.                 'regionCode' => $region->getCodeRegion(),
  7278.                 'regionName' => $region->getNomRegion(),
  7279.                 'city' => $region->getNomCommunePostal(),
  7280.             ];
  7281.         }
  7282.         return null;
  7283.     }
  7284.     /**
  7285.      * 
  7286.      * @Route("/giuili-admin/lead/{leadId}/centre/{centreId}", name="showLeadCentre", methods={"GET"})
  7287.      */
  7288.     public function showLeadCentre(int $leadIdCentre $centreId): Response
  7289.     {
  7290.         // dd("tets");
  7291.         $center $centres $this->getDoctrine()
  7292.             ->getRepository(AudioCentre::class)
  7293.             ->findOneBy(['id_centre' => $centreId->getId()]);
  7294.         $audio $center->getIdAudio();
  7295.         $motifs $this->getDoctrine()->getRepository(AudioMotif::class)
  7296.             ->findBy(['id_audio' => $audio'isDeleted' => 0]);
  7297.         return $this->render('easyadmin/leadRdv/centre_show.html.twig', [
  7298.             'audio' => $audio,
  7299.             'leadId' => $leadId,
  7300.             'centreId' => $centreId,
  7301.             'motifs' => $motifs,
  7302.         ]);
  7303.     }
  7304.     /**
  7305.      * @Route("/rdv-easyadmin", name="postRdvEasyAdmin", methods={"POST"})
  7306.      */
  7307.     public function postRdvEasyAdmin(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendarRdvSmsService $rdvSmsAppointmentCallService $Callservice): Response
  7308.     {
  7309.         $data json_decode($request->getContent(), true);
  7310.         $entityManager $this->getDoctrine()->getManager();
  7311.         $audio $this->getDoctrine()
  7312.             ->getRepository(Audio::class)
  7313.             ->findOneBy(['id' => $data["audio_id"]]);
  7314.         $leadRdv =   $this->getDoctrine()->getRepository(LeadRdv::class)
  7315.             ->find($data["lead_id"]);
  7316.         $client $this->getDoctrine()->getRepository(Client::class)
  7317.             ->find($leadRdv->getClient());
  7318.         $responses = [
  7319.             'rangeAge' => $leadRdv->getRangeAge(),
  7320.             'situations' =>  implode(", "$leadRdv->getSituationsGene()),
  7321.             'equipeAppareil' => $leadRdv->getEquipeAppareil(),
  7322.             'durationEquipe' => $leadRdv->getDurationEquipeAppareil(),
  7323.             'bilanAuditif' => $leadRdv->getBilanAuditif(),
  7324.             'ordonance' => $leadRdv->getOrdonance(),
  7325.             'dateOrdonance' => $leadRdv->getDateOrdonance(),
  7326.             'canMove' => $leadRdv->getCanMove(),
  7327.         ];
  7328.         // makes the rdv
  7329.         $rdv = new Rdv();
  7330.         $rdv->setIdAudio($audio);
  7331.         if (isset($proche)) {
  7332.             $rdv->setIdProche($proche);
  7333.         }
  7334.         if (isset($data["client_id_temp"])) {
  7335.             $rdv->setIdClientTemp($client);
  7336.         } else {
  7337.             $rdv->setIdClient($client);
  7338.         }
  7339.         $rdv->setIsMyaudio(true);
  7340.         if (isset($data["isRdvLead"])) {
  7341.             $rdv->setIsRdvLp(true);
  7342.         }
  7343.         if (isset($data["isRdvRapide"])) {
  7344.             $rdv->setIsRdvRapide(true);
  7345.         }
  7346.         if (isset($data["duree"])) {
  7347.             $rdv->setDuration($data["duree"]);
  7348.         }
  7349.         if (isset($data["color"])) {
  7350.             $rdv->setColor($data["color"]);
  7351.         }
  7352.         /** @var Centre */
  7353.         if (isset($data["centre_id"])) {
  7354.             $centre $this->getDoctrine()
  7355.                 ->getRepository(Centre::class)
  7356.                 ->findOneBy(['id' => $data["centre_id"]]);
  7357.             if ($centre == null) {
  7358.                 return new Response(json_encode(([
  7359.                     'message' => 'Error, no centre found at this id',
  7360.                     'path' => 'src/Controller/RdvController.php',
  7361.                     "status" => 400,
  7362.                 ])), 400);
  7363.             }
  7364.             /** @var AudioCentre */
  7365.             $liaison $this->getDoctrine()
  7366.                 ->getRepository(AudioCentre::class)
  7367.                 ->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
  7368.             if ($liaison == null) {
  7369.                 return new Response(json_encode(([
  7370.                     'message' => 'Error, audio isnt part of the centre',
  7371.                     'path' => 'src/Controller/RdvController.php',
  7372.                     "status" => 400,
  7373.                 ])), 400);
  7374.             }
  7375.             $rdv->setIdCentre($centre);
  7376.         } elseif (isset($data["lieu_id"]) && $audio->getIsIndie()) {
  7377.             // tries to set the lieu if it's an audio indie
  7378.             $lieu $this->getDoctrine()
  7379.                 ->getRepository(Lieu::class)
  7380.                 ->findOneBy(['id' => $data["lieu_id"], 'id_gerant' => $data["audio_id"]]);
  7381.             if ($lieu == null) {
  7382.                 return new Response(json_encode(([
  7383.                     'message' => 'Error, no lieu found at this id',
  7384.                     'path' => 'src/Controller/RdvController.php',
  7385.                     "status" => 400,
  7386.                 ])), 400);
  7387.             }
  7388.             $rdv->setIdLieu($lieu);
  7389.         } else {
  7390.             return new Response(json_encode(([
  7391.                 'message' => 'Error, no lieu/centre id',
  7392.                 'path' => 'src/Controller/RdvController.php',
  7393.                 "status" => 400,
  7394.             ])), 400);
  7395.         }
  7396.         /** @var Motif */
  7397.         $motif $this->getDoctrine()
  7398.             ->getRepository(Motif::class)
  7399.             ->find($data["motif_id"]);
  7400.         if ($motif == null) {
  7401.             return new Response(json_encode(([
  7402.                 'message' => 'Error, no motif found at this id',
  7403.                 'path' => 'src/Controller/RdvController.php',
  7404.                 "status" => 400,
  7405.             ])), 400);
  7406.         }
  7407.         /** @var AudioMotif */
  7408.         $audioMotif $this->getDoctrine()
  7409.             ->getRepository(AudioMotif::class)
  7410.             ->findOneBy(["id_audio" => $audio->getId(), "id_motif" => $data["motif_id"]]);
  7411.         if ($audioMotif == null) {
  7412.             return new Response(json_encode(([
  7413.                 'message' => 'Error, no motif of this id found at this audio',
  7414.                 'path' => 'src/Controller/RdvController.php',
  7415.                 "status" => 400,
  7416.             ])), 400);
  7417.         }
  7418.         // remove the taken schedule by rdv to make sure there is no overlap
  7419.         $data["date"] = str_replace("h"":"$data["date"]);
  7420.         $date \DateTime::createFromFormat("Y-m-d\TH:i"$data["date"]);
  7421.         if (isset($data["note"])) {
  7422.             $rdv->setNote($data["note"]);
  7423.         }
  7424.         $date \DateTime::createFromFormat("Y-m-d\TH:i"$data["date"]);
  7425.         $rdv->setDate($date);
  7426.         $rdv->setDateCreation(\DateTime::createFromFormat("d/m/Y H:i"date('d/m/Y H:i')));
  7427.         /** @var EtatRdv */
  7428.         $etat $this->getDoctrine()
  7429.             ->getRepository(EtatRdv::class)
  7430.             ->findOneBy(['id' => $data["etat_id"]]);
  7431.         if ($etat == null) {
  7432.             return new Response(json_encode(([
  7433.                 'message' => 'Error, no etat found at this id',
  7434.                 'path' => 'src/Controller/RdvController.php',
  7435.                 "status" => 400,
  7436.             ])), 400);
  7437.         }
  7438.         $rdv->setIdEtat($etat);
  7439.         $rdv->setIdMotif($motif);
  7440.         $rdv->setIsAbsence(0);
  7441.         $rdv->setCacher(0);
  7442.         $entityManager $this->getDoctrine()->getManager();
  7443.         $entityManager->persist($rdv);
  7444.         $leadRdv->setRdv($rdv);
  7445.         $leadStatus $this->entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'rdv_valider']);
  7446.         $leadRdv->setLeadStatus($leadStatus);
  7447.         $entityManager->flush();
  7448.         /// SMSEMAIL A décommenter pour autoriser l'envoi de sms / email à la création de rdv par l'audio / le client SMSEMAIL ///
  7449.         $date $rdv->getDate();
  7450.         $smsDate $date->format('d-m-Y H:i');
  7451.         $locale 'fr_FR';
  7452.         $formatter = new IntlDateFormatter(
  7453.             $locale,
  7454.             IntlDateFormatter::FULL,
  7455.             IntlDateFormatter::SHORT,
  7456.             null,
  7457.             IntlDateFormatter::GREGORIAN,
  7458.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  7459.         );
  7460.         $smsDateLongFormat $formatter->format($date);
  7461.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  7462.         $client->setIdCentre($rdv->getIdCentre());
  7463.         $client->setIdAudio($rdv->getIdAudio());
  7464.         $entityManager->persist($client);
  7465.         $entityManager->flush();
  7466.         // client notif mail Sms
  7467.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  7468.         $frenchDate ucfirst($frenchDate);
  7469.         $params = array(
  7470.             "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  7471.             "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  7472.             "date" => $smsDateLongFormat,
  7473.             "RdvDate" => $smsDateLongFormat,
  7474.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  7475.             "centerName" => $rdv->getIdCentre()->getName(),
  7476.             "prenom" => $client->getName(),
  7477.             "centerAddress" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  7478.             "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  7479.             'motif' => $rdv->getIdMotif()->getTitre(),
  7480.             "centerCity" => $rdv->getIdCentre()->getCity(),
  7481.             "audioName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  7482.             'titre' => "Votre rendez-vous est validé le " substr($smsDate010) . " à "  substr($smsDate1115),
  7483.             "position" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  7484.             "address" => $rdv->getIdCentre()->getAddress(),
  7485.             "postal" => $rdv->getIdCentre()->getPostale(),
  7486.             "city" => $rdv->getIdCentre()->getCity(),
  7487.             "clientEmail" => $client->getMail(),
  7488.             "clientPassword" => isset($data["passwordGenerated"]) ? $data["passwordGenerated"] : null,
  7489.             "clientAddress" => $client->getAddress(),
  7490.             "clientPostal" => $client->getPostal(),
  7491.             "clientCity" => $client->getCity(),
  7492.             "audioName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  7493.             "frenchDate" => $frenchDate,
  7494.             "heure" => substr($smsDate1115),
  7495.             "centerName" => $rdv->getIdCentre()->getName(),
  7496.             "audioMail" => $rdv->getIdAudio()->getMail(),
  7497.             "modifUrl" => "{$_ENV['BASE_client']}mes-rendez-vous",
  7498.         );
  7499.         $paramsPatient $params;
  7500.         $isNew false;
  7501.         if (isset($data["isLead"]) && isset($data["passwordGenerated"]) != null) {
  7502.             $subject "✅Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  7503.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject189);
  7504.             $isNew true;
  7505.         } else {
  7506.             $subject "Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  7507.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject181);
  7508.         }
  7509.         $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.";
  7510.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  7511.         // audio Notif mail SMS
  7512.         $birthday $rdv->getIdClient()->getBirthdate();
  7513.         $params = array(
  7514.             "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  7515.             "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  7516.             "date" => substr($smsDate010),
  7517.             "heure" => substr($smsDate1115),
  7518.             "mail" => $client->getMail(),
  7519.             "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  7520.             'telClient' => $client->getPhone(),
  7521.             'phone' => $client->getPhone(),
  7522.             'clientCivilite' => $client->getCivilite(),
  7523.             'clientNom' => $client->getLastname(),
  7524.             'clientPrenom' => $client->getName(),
  7525.             'clientPostal' => $client->getPostal(),
  7526.             'clientMail' => $client->getMail(),
  7527.             'clientPhone' => $client->getPhone(),
  7528.             'motif' => $rdv->getIdMotif()->getTitre(),
  7529.             'birthdate' => $client->getBirthdate() ? $client->getBirthdate()->format("d/m/Y") : null,
  7530.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  7531.             'centerName' => $rdv->getIdCentre()->getName(),
  7532.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  7533.             'centerCity' => $rdv->getIdCentre()->getCity(),
  7534.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  7535.             'idPatient' => $client->getId(),
  7536.             'proUrl' => "{$_ENV['BASE_logiciel']}",
  7537.             'frenchDate' => $frenchDate,
  7538.             'responses' => $responses,
  7539.         );
  7540.         $templateEmail 182;
  7541.         if (!empty($data['canMove'])) {
  7542.             $templateEmail 197;
  7543.         }
  7544.         $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  7545.         $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  7546.         if ($rdv->getIdAudio()->getConfirmRdvMail()) {
  7547.             $subject "✅ Nouveau Rendez-vous My Audio le " $frenchDate " à " substr($smsDate1115);
  7548.             $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject$templateEmail);
  7549.         }
  7550.         if ($rdv->getIdAudio()->getConfirmRdvSms()) {
  7551.             $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.";
  7552.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  7553.         }
  7554.         $age null;
  7555.         if ($client->getBirthdate()) {
  7556.             $age $client->getBirthdate()->diff(new \DateTime())->y;
  7557.         }
  7558.         // Génère le PDF à partir d’un template
  7559.         $pdfContent $this->generatePdf(
  7560.             'pdf/rdv_recap.html.twig',
  7561.             [
  7562.                 'id' => $client->getId() ?? '',
  7563.                 'nom' => $client->getName() ?? '',
  7564.                 'prenom' => $client->getLastname() ?? '',
  7565.                 'birthday' =>  $client->getBirthdate() ? $client->getBirthdate()->format("d/m/Y") : null,
  7566.                 'age' => $age,
  7567.                 'adresse' => $client->getAddress() ?? '',
  7568.                 'postal' => $client->getPostal() ?? '',
  7569.                 'city' => $client->getCity() ?? '',
  7570.                 'phone' => $client->getPhone() ?? '',
  7571.                 'mail' => $client->getMail() ?? '',
  7572.                 'centerName' => $rdv->getIdCentre()->getName() ?? '',
  7573.                 "date" => substr($smsDate010) ?? '',
  7574.                 "heure" => substr($smsDate1115) ?? '',
  7575.                 'duration' => $rdv->getDuration(),
  7576.                 "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  7577.                 'motif' => $rdv->getIdMotif() ? $rdv->getIdMotif()->getTitre() : '',
  7578.                 'situations' => $this->formatImploded($leadRdv->getSituationsGene()),
  7579.                 'IntensiteGen' => $leadRdv->getIntensiteGene() ?? '',
  7580.                 'devicePref' => $this->formatImploded($leadRdv->getPreferenceDevice()),
  7581.                 'deviceModelPref' =>  implode(", "$leadRdv->getDeviceModelPreference()),
  7582.                 'criterePrincipal' => $this->formatImploded($leadRdv->getCriterePrincipal()),
  7583.                 'accoupheneCote' =>  $leadRdv->getAcoupheneCote() ?? '',
  7584.                 'originePerte' => $this->formatImploded($leadRdv->getOriginePerte()),
  7585.                 'diabete' =>  $leadRdv->getDiabete() ?? '',
  7586.                 'hypertension' =>  $leadRdv->getHypertension() ?? '',
  7587.                 'mutuelle' =>  $leadRdv->getMutuelle() ?? '',
  7588.                 'nameMutuelle' =>  $leadRdv->getNameMutuelle() ?? '',
  7589.                 'priseEnCharge' => $leadRdv->getPriseEnCharge() ?? '',
  7590.                 'budget' => $leadRdv->getBudget() ?? '',
  7591.                 'equipeAppareil' => $leadRdv->getEquipeAppareil() ?? '',
  7592.                 'durationEquipe' => $leadRdv->getDurationEquipeAppareil() ?? '',
  7593.                 'bilanAuditif' => $leadRdv->getBilanAuditif() ?? '',
  7594.                 'ordonance' => $leadRdv->getOrdonance() ?? '',
  7595.                 'dateOrdonance' => $leadRdv->getDateOrdonance() ?? '',
  7596.                 'canMove' => $leadRdv->getCanMove() ?? '',
  7597.                 'comment' => $leadRdv->getComment() ?? '',
  7598.             ],
  7599.             $this->getParameter('kernel.project_dir') . '/public/assets/pdf/recap-rdv-myaudio.pdf'
  7600.         );
  7601.         $this->sendEmailWithPdfAttachmentThenDelete(
  7602.             $params,
  7603.             $mailAudio,
  7604.             $client->getName(),
  7605.             $subject,
  7606.             $templateEmail// ID du template Sendinblue
  7607.             $pdfContent
  7608.         );
  7609.         // send notif to admin
  7610.         $paramsSourceLead = [
  7611.             'trafficSource' => "EasyAdmin",
  7612.         ];
  7613.         $paramsAdmin = array(
  7614.             "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  7615.             "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  7616.             "RdvDate" => substr($smsDate010),
  7617.             "heure" => substr($smsDate1115),
  7618.             "clientMail" => $client->getMail(),
  7619.             "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  7620.             'telClient' => $client->getPhone(),
  7621.             'clientNom' => $client->getLastname(),
  7622.             'clientPrenom' => $client->getName(),
  7623.             'clientCivilite' => $client->getCivilite(),
  7624.             'clientPostal' => $client->getPostal(),
  7625.             'clientPhone' => $client->getPhone(),
  7626.             'motif' => $rdv->getIdMotif()->getTitre(),
  7627.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  7628.             'centerName' => $rdv->getIdCentre()->getName(),
  7629.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  7630.             'centerCity' => $rdv->getIdCentre()->getCity(),
  7631.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  7632.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  7633.             'date' => substr($smsDate010),
  7634.             'urlApi' => "{$_ENV['BASE_API']}",
  7635.             'clientId' => $client->getId(),
  7636.             'centerId' => $rdv->getIdCentre()->getId(),
  7637.             'frenchDate' => $frenchDate,
  7638.             'responses' => $responses,
  7639.             'paramsSourceLead' => $paramsSourceLead
  7640.         );
  7641.         $subject "Nouveau RDV MA | RR - " $rdv->getIdCentre()->getName();
  7642.         $templateEmail 183;
  7643.         if (!empty($data['canMove'])) {
  7644.             $templateEmail 190;
  7645.         }
  7646.         $publicFunction->sendEmail($paramsAdmin"contact@myaudio.fr""my audio"$subject$templateEmail);
  7647.         $publicFunction->sendEmail($paramsAdmin"lead.myaudio@gmail.com""my audio"$subject$templateEmail);
  7648.         $specificSubscription $this->getDoctrine()
  7649.              ->getRepository(SpecificSubscription::class)
  7650.              ->findOneBy(['audio' => $audio]);
  7651.       if ($specificSubscription && $specificSubscription->getContractCategory()) {
  7652.         $contractCategory $specificSubscription->getContractCategory();
  7653.       if ($contractCategory->getName() === "OPTICAL CENTER SUCCURSALE") {
  7654.         $publicFunction->sendEmail($paramsAdmin"christel.montagne@optical-center.com""my audio"$subject246);
  7655.          }
  7656.        }
  7657.         try {
  7658.             $Callservice->handleCallCenterAfterRdv(
  7659.                 $rdv
  7660.             );
  7661.             $rdv->setIsNotificationRdvCallSent(1);
  7662.             $this->entityManager->flush();
  7663.         } catch (\Exception $e) {
  7664.             $this->logger->error("Erreur lors de l'appel de notification pour le RDV #{$rdv->getId()}: " $e->getMessage());
  7665.         }
  7666.         // google calendar post
  7667.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  7668.             ->findBy(array('audio' => $audio->getId()));
  7669.         $data['rdv'] = $rdv->getId();
  7670.         foreach ($synchronisations as $synchronisation) {
  7671.             if (!$synchronisation->getIsDeleted()) {
  7672.                 $googleCalendar->checkAndRefreshAccessToken($synchronisation);
  7673.                 $googleCalendar->createEvent($synchronisation$data);
  7674.             }
  7675.         }
  7676.         return new Response(json_encode(([
  7677.             "id" => $rdv->getId(),
  7678.             "motif_id" => $rdv->getIdMotif()->getId(),
  7679.             "audio_id" => $rdv->getIdAudio()->getId(),
  7680.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  7681.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  7682.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  7683.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  7684.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  7685.             "testclient" => $rdv->getTestClient() ? [
  7686.                 "result" => $rdv->getTestClient()->getResultTonal(),
  7687.                 "date" => $rdv->getTestClient()->getDate(),
  7688.                 "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  7689.             ] : null,
  7690.             "duration" => $audioMotif->getDuration(),
  7691.             "consigne" => $audioMotif->getConsigne(),
  7692.             "etat_id" => $rdv->getIdEtat()->getId(),
  7693.             "date" => $rdv->getDate(),
  7694.             "comment" => $rdv->getComment(),
  7695.             "centerName" => $rdv->getIdCentre()->getName(),
  7696.             "review" => $rdv->getReview(),
  7697.             "note" => $rdv->getNote(),
  7698.             "status" => 200,
  7699.             "paramsPatient" => $paramsPatient,
  7700.             "isNew" => $isNew,
  7701.         ])));
  7702.     }
  7703.     private function generatePdf(string $template, array $data = [], string $outputPath): string
  7704.     {
  7705.         // Render le contenu HTML avec Twig
  7706.         $html $this->twig->render($template$data);
  7707.         // Configurer Dompdf
  7708.         $options = new Options();
  7709.         $options->set('defaultFont''Arial');
  7710.         $dompdf = new Dompdf($options);
  7711.         $dompdf->loadHtml($html);
  7712.         $dompdf->setPaper('A4''portrait');
  7713.         $dompdf->render();
  7714.         // Sauvegarder le PDF
  7715.         file_put_contents($outputPath$dompdf->output());
  7716.         return $outputPath// Renvoie le chemin du fichier PDF généré
  7717.     }
  7718.     private function sendEmailWithPdfAttachmentThenDelete(
  7719.         array $params,
  7720.         string $mail,
  7721.         string $name,
  7722.         string $subject,
  7723.         int $templateId,
  7724.         string $pdfFilePath
  7725.     ): void {
  7726.         // Lire et encoder le contenu du PDF
  7727.         $attachment = [
  7728.             "name" => basename($pdfFilePath),
  7729.             "content" => base64_encode(file_get_contents($pdfFilePath)),
  7730.         ];
  7731.         // Construire les données pour l’API Sendinblue
  7732.         $data = [
  7733.             "sender" => [
  7734.                 "email" => 'noreply@myaudio.fr',
  7735.                 "name" => 'My Audio',
  7736.             ],
  7737.             "to" => [
  7738.                 [
  7739.                     "email" => $mail,
  7740.                     "name" => $name,
  7741.                 ],
  7742.             ],
  7743.             "subject" => $subject,
  7744.             "templateId" => $templateId,
  7745.             "params" => $params,
  7746.             "attachment" => [$attachment],
  7747.         ];
  7748.         // Envoi via cURL
  7749.         $ch curl_init();
  7750.         curl_setopt($chCURLOPT_URL'https://api.sendinblue.com/v3/smtp/email');
  7751.         curl_setopt($chCURLOPT_RETURNTRANSFER1);
  7752.         curl_setopt($chCURLOPT_POST1);
  7753.         curl_setopt($chCURLOPT_POSTFIELDSjson_encode($data));
  7754.         $headers = [
  7755.             'Accept: application/json',
  7756.             'Api-Key: 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',
  7757.             'Content-Type: application/json',
  7758.         ];
  7759.         curl_setopt($chCURLOPT_HTTPHEADER$headers);
  7760.         $result curl_exec($ch);
  7761.         if (curl_errno($ch)) {
  7762.             echo 'Erreur email : ' curl_error($ch);
  7763.         }
  7764.         curl_close($ch);
  7765.         // Supprimer le PDF après envoi
  7766.         if (file_exists($pdfFilePath)) {
  7767.             unlink($pdfFilePath);
  7768.         }
  7769.     }
  7770.     private function formatImploded(array $data): string
  7771.     {
  7772.         return implode(', 'array_map(function ($item) {
  7773.             return str_replace('_'' '$item);
  7774.         }, $data));
  7775.     }
  7776.     /**
  7777.      * 
  7778.      * @Route("/admin/rdv/export-pdf-form", name="admin_rdv_export_pdf_form", methods={"GET", "POST"})
  7779.      */
  7780.     public function exportPdfForm(Request $request): Response
  7781.     {
  7782.         $form $this->createFormBuilder()
  7783.             ->add('startDate'\Symfony\Component\Form\Extension\Core\Type\DateType::class, [
  7784.                 'label' => 'Date de début',
  7785.                 'widget' => 'single_text',
  7786.                 'html5' => true,
  7787.                 'required' => true,
  7788.             ])
  7789.             ->add('endDate'\Symfony\Component\Form\Extension\Core\Type\DateType::class, [
  7790.                 'label' => 'Date de fin',
  7791.                 'widget' => 'single_text',
  7792.                 'html5' => true,
  7793.                 'required' => true,
  7794.             ])
  7795.             ->add('format'\Symfony\Component\Form\Extension\Core\Type\ChoiceType::class, [
  7796.                 'label' => 'Format d\'export',
  7797.                 'choices' => [
  7798.                     'PDF' => 'pdf',
  7799.                     'Excel' => 'excel',
  7800.                 ],
  7801.                 'expanded' => false,
  7802.                 'multiple' => false,
  7803.                 'required' => true,
  7804.             ])
  7805.             ->getForm();
  7806.         //dd($request);
  7807.         $form->handleRequest($request);
  7808.         if ($form->isSubmitted() && $form->isValid()) {
  7809.             $data $form->getData();
  7810.             $start $data['startDate']->format('Y-m-d');
  7811.             $end $data['endDate']->format('Y-m-d');
  7812.             if ($data['format'] === 'pdf') {
  7813.                 return $this->redirectToRoute('admin_rdv_export_pdf', [
  7814.                     'startDate' => $start,
  7815.                     'endDate' => $end,
  7816.                 ]);
  7817.             } else {
  7818.                 return $this->redirectToRoute('admin_rdv_export_excel', [
  7819.                     'startDate' => $start,
  7820.                     'endDate' => $end,
  7821.                 ]);
  7822.             }
  7823.         }
  7824.         return $this->render('easyadmin/rdv/export_pdf_form.html.twig', [
  7825.             'form' => $form->createView(),
  7826.         ]);
  7827.     }
  7828.     /**
  7829.      * 
  7830.      * @Route("/optical/rdv/export-pdf-form", name="optical_rdv_export_pdf_form", methods={"GET", "POST"})
  7831.      */
  7832.     public function exportOpticalPdfForm(Request $request): Response
  7833.     {
  7834.         $form $this->createFormBuilder()
  7835.             ->add('startDate'\Symfony\Component\Form\Extension\Core\Type\DateType::class, [
  7836.                 'label' => 'Date de début',
  7837.                 'widget' => 'single_text',
  7838.                 'html5' => true,
  7839.                 'required' => true,
  7840.             ])
  7841.             ->add('endDate'\Symfony\Component\Form\Extension\Core\Type\DateType::class, [
  7842.                 'label' => 'Date de fin',
  7843.                 'widget' => 'single_text',
  7844.                 'html5' => true,
  7845.                 'required' => true,
  7846.             ])
  7847.             ->add('format'\Symfony\Component\Form\Extension\Core\Type\ChoiceType::class, [
  7848.                 'label' => 'Format d\'export',
  7849.                 'choices' => [
  7850.                     'PDF' => 'pdf',
  7851.                     'Excel' => 'excel',
  7852.                 ],
  7853.                 'expanded' => false,
  7854.                 'multiple' => false,
  7855.                 'required' => true,
  7856.             ])
  7857.             ->getForm();
  7858.         //dd($request);
  7859.         $form->handleRequest($request);
  7860.         if ($form->isSubmitted() && $form->isValid()) {
  7861.             $data $form->getData();
  7862.             $start $data['startDate']->format('Y-m-d');
  7863.             $end $data['endDate']->format('Y-m-d');
  7864.             if ($data['format'] === 'pdf') {
  7865.                 return $this->redirectToRoute('optical_rdv_export_pdf', [
  7866.                     'startDate' => $start,
  7867.                     'endDate' => $end,
  7868.                 ]);
  7869.             } else {
  7870.                 return $this->redirectToRoute('optical_rdv_export_excel', [
  7871.                     'startDate' => $start,
  7872.                     'endDate' => $end,
  7873.                 ]);
  7874.             }
  7875.         }
  7876.         return $this->render('easyadmin/rdv/export_pdf_form.html.twig', [
  7877.             'form' => $form->createView(),
  7878.         ]);
  7879.     }
  7880.     /**
  7881.      * @Route("/admin/lead-rdv/update-status", name="admin_lead_rdv_update_status", methods={"POST"})
  7882.      */
  7883.     public function updateStatus(Request $request): JsonResponse
  7884.     {
  7885.         // Récupérer les données envoyées en AJAX
  7886.         $data json_decode($request->getContent(), true);
  7887.         $leadId $data['leadId'] ?? null;
  7888.         $statusId $data['statusId'] ?? null;
  7889.         if (!$leadId || !$statusId) {
  7890.             return new JsonResponse(['success' => false'message' => 'Données manquantes'], 400);
  7891.         }
  7892.         // Récupérer le lead et le statut
  7893.         $lead $this->entityManager->getRepository(LeadRdv::class)->find($leadId);
  7894.         $status $this->entityManager->getRepository(LeadStatus::class)->find($statusId);
  7895.         if (!$lead || !$status) {
  7896.             return new JsonResponse(['success' => false'message' => 'Lead ou statut introuvable'], 404);
  7897.         }
  7898.         // Mettre à jour le statut du lead
  7899.         $lead->setLeadStatus($status);
  7900.         $this->entityManager->flush();
  7901.         return new JsonResponse(['success' => true]);
  7902.     }
  7903.     /**
  7904.      * @Route("/admin/rdv/update-client-status", name="admin_rdv_update_client_status", methods={"POST"})
  7905.      */
  7906.     public function updateClientStatus(Request $request): JsonResponse
  7907.     {
  7908.         $data json_decode($request->getContent(), true);
  7909.         $rdvId $data['rdvId'] ?? null;
  7910.         $statusId $data['statusId'] ?? null;
  7911.         if (!$rdvId || !$statusId) {
  7912.             return new JsonResponse(['success' => false'message' => 'Données manquantes'], 400);
  7913.         }
  7914.         // Récupérer le RDV
  7915.         $rdv $this->entityManager->getRepository(Rdv::class)->find($rdvId);
  7916.         if (!$rdv) {
  7917.             return new JsonResponse(['success' => false'message' => 'RDV non trouvé'], 404);
  7918.         }
  7919.         // Récupérer le statut
  7920.         $clientStatus $this->entityManager->getRepository(ClientStatus::class)->find($statusId);
  7921.         if (!$clientStatus) {
  7922.             return new JsonResponse(['success' => false'message' => 'Statut non trouvé'], 404);
  7923.         }
  7924.         // Mettre à jour le client
  7925.         $client $rdv->getIdClient();
  7926.         if ($client) {
  7927.             $client->setClientStatus($clientStatus);
  7928.             $this->entityManager->flush();
  7929.             // Si le statut est "Facturé", lancer la facturation
  7930.             if ((int)$statusId === 2) {
  7931.                 // Réutiliser la méthode de facturation existante
  7932.                 $crudController $this->container->get(RdvMyAudioCrudController::class);
  7933.                 $crudController->billing($rdv);
  7934.             }
  7935.             return new JsonResponse(['success' => true]);
  7936.         }
  7937.         return new JsonResponse(['success' => false'message' => 'Client non trouvé'], 404);
  7938.     }
  7939.     /**
  7940.      * @Route("/admin/rdv/update-rdv-status", name="admin_rdv_update_status", methods={"POST"})
  7941.      */
  7942.     public function updateRdvStatus(Request $requestEntityManagerInterface $entityManager): JsonResponse
  7943.     {
  7944.         $data json_decode($request->getContent(), true);
  7945.         $rdvId $data['rdvId'] ?? null;
  7946.         $statusId $data['statusId'] ?? null;
  7947.         if (!$rdvId || !$statusId) {
  7948.             return new JsonResponse(['success' => false'message' => 'Données manquantes'], 400);
  7949.         }
  7950.         // Récupérer le RDV
  7951.         $rdv $entityManager->getRepository(Rdv::class)->find($rdvId);
  7952.         if (!$rdv) {
  7953.             return new JsonResponse(['success' => false'message' => 'RDV non trouvé'], 404);
  7954.         }
  7955.         // Récupérer le statut
  7956.         $etatRdv $entityManager->getRepository(EtatRdv::class)->find($statusId);
  7957.         if (!$etatRdv) {
  7958.             return new JsonResponse(['success' => false'message' => 'Statut non trouvé'], 404);
  7959.         }
  7960.         // Mettre à jour le statut du RDV
  7961.         $rdv->setIdEtat($etatRdv);
  7962.         $entityManager->flush();
  7963.         return new JsonResponse(['success' => true]);
  7964.     }
  7965.     /**
  7966.      * @Route("/admin/rdv/export-pdf/{startDate}/{endDate}", name="admin_rdv_export_pdf", methods={"GET"})
  7967.      */
  7968.     public function exportPdfFromDate(string $startDatestring $endDateKernelInterface $kernel): Response
  7969.     {
  7970.         $start = new \DateTimeImmutable($startDate);
  7971.         $end = new \DateTimeImmutable($endDate);
  7972.         $today = new \DateTimeImmutable();
  7973.         $rdvs $this->rdvRepository->findBySinceDateAndMyAudio($start$end);
  7974.         $html "
  7975.     <html>
  7976.     <head>
  7977.         <style>
  7978.             body { font-family: Arial, sans-serif; font-size: 13px; }
  7979.             table { width: 100%; border-collapse: collapse; font-size: 11px; }
  7980.             th, td { border: 1px solid #000; padding: 5px; text-align: left; }
  7981.             th { font-weight: bold; }
  7982.             h1 { font-size: 14px; }
  7983.         </style>
  7984.     </head>
  7985.     <body>
  7986.         <h1>Rendez-vous My Audio du " $start->format('d/m/Y') . " au " $end->format('d/m/Y') . "</h1>
  7987.         <table cellspacing='0' cellpadding='5'>
  7988.             <thead>
  7989.                 <tr>
  7990.                     <th>ID du RDV</th>
  7991.                     <th>Date du RDV</th>
  7992.                     <th>Jours écoulés</th>
  7993.                     <th>Statut RDV</th>
  7994.                     <th>Nom patient</th>
  7995.                     <th>Téléphone patient</th>
  7996.                     <th>Statut patient</th>
  7997.                     <th>Centre</th>
  7998.                     <th>Téléphone Centre</th>
  7999.                     <th>Adresse</th>
  8000.                     <th>Nom Audio</th>
  8001.                 </tr>
  8002.             </thead>
  8003.             <tbody>";
  8004.         foreach ($rdvs as $rdv) {
  8005.             $dateRdv $rdv->getDate();
  8006.             $joursEcoules $dateRdv->diff($today)->days;
  8007.             $client $rdv->getIdClient();
  8008.             $centre $rdv->getIdCentre();
  8009.             $etat $rdv->getIdEtat();
  8010.             $audio $rdv->getIdAudio();
  8011.             $html .= "<tr>
  8012.             <td>" $rdv->getId() . "</td>
  8013.             <td>" $dateRdv->format('d/m/Y H:i') . "</td>
  8014.             <td>" $joursEcoules " jours</td>
  8015.             <td>" . ($etat htmlspecialchars($etat->getLibelle()) : 'Non défini') . "</td>
  8016.             <td>" . ($client htmlspecialchars($client->getName() . ' ' $client->getLastname()) : '') . "</td>
  8017.             <td>" . ($client htmlspecialchars($client->getPhone()) : '') . "</td>
  8018.             <td>" . ($client && $client->getClientStatus() ? htmlspecialchars($client->getClientStatus()->getLibelle()) : 'Non défini') . "</td>
  8019.             <td>" . ($centre htmlspecialchars($centre->getName()) : '') . "</td>
  8020.             <td>" . ($centre htmlspecialchars($centre->getPhone()) : '') . "</td>
  8021.             <td>" . ($centre htmlspecialchars($centre->getAddress() . ', ' $centre->getPostale() . ' ' $centre->getCity()) : '') . "</td>
  8022.             <td>" . ($audio htmlspecialchars($audio->getCivilite() . ' ' $audio->getName() . ' ' $audio->getLastname()) : '') . "</td>
  8023.         </tr>";
  8024.         }
  8025.         $html .= "</tbody></table></body></html>";
  8026.         // Configuration et rendu du PDF
  8027.         $options = new Options();
  8028.         $options->set('defaultFont''Arial');
  8029.         $dompdf = new Dompdf($options);
  8030.         $dompdf->loadHtml($html);
  8031.         $dompdf->setPaper('A4''landscape');
  8032.         $dompdf->render();
  8033.         // Création du dossier s'il n'existe pas
  8034.         $projectDir $kernel->getProjectDir();
  8035.         $outputDir $projectDir '/public/assets/pdf/rdv';
  8036.         $filesystem = new Filesystem();
  8037.         if (!$filesystem->exists($outputDir)) {
  8038.             $filesystem->mkdir($outputDir0775);
  8039.         }
  8040.         $filenameDate $start->format('Y-m-d') . '_to_' $end->format('Y-m-d');
  8041.         $outputPath "$outputDir/rdvs-$filenameDate.pdf";
  8042.         file_put_contents($outputPath$dompdf->output());
  8043.         return new Response($dompdf->output(), 200, [
  8044.             'Content-Type' => 'application/pdf',
  8045.             'Content-Disposition' => 'attachment; filename="rdvs-' $filenameDate '.pdf"',
  8046.         ]);
  8047.     }
  8048.     /**
  8049.      * @Route("/optical/rdv/export-pdf/{startDate}/{endDate}", name="optical_rdv_export_pdf", methods={"GET"})
  8050.      */
  8051.     public function exportOpticalPdfFromDate(string $startDatestring $endDateKernelInterface $kernel): Response
  8052.     {
  8053.         $start = new \DateTimeImmutable($startDate);
  8054.         $end = new \DateTimeImmutable($endDate);
  8055.         $today = new \DateTimeImmutable();
  8056.         $rdvs $this->rdvRepository->findOpticalBySinceDateAndMyAudio($start$end);
  8057.         $html "
  8058.     <html>
  8059.     <head>
  8060.         <style>
  8061.             body { font-family: Arial, sans-serif; font-size: 13px; }
  8062.             table { width: 100%; border-collapse: collapse; font-size: 11px; }
  8063.             th, td { border: 1px solid #000; padding: 5px; text-align: left; }
  8064.             th { font-weight: bold; }
  8065.             h1 { font-size: 14px; }
  8066.         </style>
  8067.     </head>
  8068.     <body>
  8069.         <h1>Rendez-vous My Audio du " $start->format('d/m/Y') . " au " $end->format('d/m/Y') . "</h1>
  8070.         <table cellspacing='0' cellpadding='5'>
  8071.             <thead>
  8072.                 <tr>
  8073.                     <th>ID du RDV</th>
  8074.                     <th>Date du RDV</th>
  8075.                     <th>Jours écoulés</th>
  8076.                     <th>Statut RDV</th>
  8077.                     <th>Nom patient</th>
  8078.                     <th>Téléphone patient</th>
  8079.                     <th>Statut patient</th>
  8080.                     <th>Centre</th>
  8081.                     <th>Téléphone Centre</th>
  8082.                     <th>Adresse</th>
  8083.                     <th>Nom Audio</th>
  8084.                 </tr>
  8085.             </thead>
  8086.             <tbody>";
  8087.         foreach ($rdvs as $rdv) {
  8088.             $dateRdv $rdv->getDate();
  8089.             $joursEcoules $dateRdv->diff($today)->days;
  8090.             $client $rdv->getIdClient();
  8091.             $centre $rdv->getIdCentre();
  8092.             $etat $rdv->getIdEtat();
  8093.             $audio $rdv->getIdAudio();
  8094.             $html .= "<tr>
  8095.             <td>" $rdv->getId() . "</td>
  8096.             <td>" $dateRdv->format('d/m/Y H:i') . "</td>
  8097.             <td>" $joursEcoules " jours</td>
  8098.             <td>" . ($etat htmlspecialchars($etat->getLibelle()) : 'Non défini') . "</td>
  8099.             <td>" . ($client htmlspecialchars($client->getName() . ' ' $client->getLastname()) : '') . "</td>
  8100.             <td>" . ($client htmlspecialchars($client->getPhone()) : '') . "</td>
  8101.             <td>" . ($client && $client->getClientStatus() ? htmlspecialchars($client->getClientStatus()->getLibelle()) : 'Non défini') . "</td>
  8102.             <td>" . ($centre htmlspecialchars($centre->getName()) : '') . "</td>
  8103.             <td>" . ($centre htmlspecialchars($centre->getPhone()) : '') . "</td>
  8104.             <td>" . ($centre htmlspecialchars($centre->getAddress() . ', ' $centre->getPostale() . ' ' $centre->getCity()) : '') . "</td>
  8105.             <td>" . ($audio htmlspecialchars($audio->getCivilite() . ' ' $audio->getName() . ' ' $audio->getLastname()) : '') . "</td>
  8106.         </tr>";
  8107.         }
  8108.         $html .= "</tbody></table></body></html>";
  8109.         // Configuration et rendu du PDF
  8110.         $options = new Options();
  8111.         $options->set('defaultFont''Arial');
  8112.         $dompdf = new Dompdf($options);
  8113.         $dompdf->loadHtml($html);
  8114.         $dompdf->setPaper('A4''landscape');
  8115.         $dompdf->render();
  8116.         // Création du dossier s'il n'existe pas
  8117.         $projectDir $kernel->getProjectDir();
  8118.         $outputDir $projectDir '/public/assets/pdf/rdv';
  8119.         $filesystem = new Filesystem();
  8120.         if (!$filesystem->exists($outputDir)) {
  8121.             $filesystem->mkdir($outputDir0775);
  8122.         }
  8123.         $filenameDate $start->format('Y-m-d') . '_to_' $end->format('Y-m-d');
  8124.         $outputPath "$outputDir/rdvs-$filenameDate.pdf";
  8125.         file_put_contents($outputPath$dompdf->output());
  8126.         return new Response($dompdf->output(), 200, [
  8127.             'Content-Type' => 'application/pdf',
  8128.             'Content-Disposition' => 'attachment; filename="rdvs-' $filenameDate '.pdf"',
  8129.         ]);
  8130.     }
  8131.     /**
  8132.      * 
  8133.      * @Route("/admin/rdv/export/excel/{startDate}/{endDate}", name="admin_rdv_export_excel", methods={"GET"})
  8134.      */
  8135.     public function exportExcelFromDate(string $startDatestring $endDate): Response
  8136.     {
  8137.         $start = new \DateTimeImmutable($startDate);
  8138.         $end = new \DateTimeImmutable($endDate);
  8139.         $rdvs $this->rdvRepository->findBySinceDateAndMyAudio($start$end);
  8140.         $spreadsheet = new Spreadsheet();
  8141.         $sheet $spreadsheet->getActiveSheet();
  8142.         // Headers
  8143.         $sheet->fromArray([
  8144.             'ID du RDV',
  8145.             'Date du RDV',
  8146.             'Jours écoulés',
  8147.             'Statut RDV',
  8148.             'Nom patient',
  8149.             'Téléphone patient',
  8150.             'Statut patient',
  8151.             'Centre',
  8152.             'Téléphone Centre',
  8153.             'Adresse',
  8154.             'Nom Audio'
  8155.         ], null'A1');
  8156.         $today = new \DateTimeImmutable();
  8157.         $row 2;
  8158.         foreach ($rdvs as $rdv) {
  8159.             $dateRdv $rdv->getDate();
  8160.             $joursEcoules $dateRdv->diff($today)->days;
  8161.             $client $rdv->getIdClient();
  8162.             $centre $rdv->getIdCentre();
  8163.             $etat $rdv->getIdEtat();
  8164.             $sheet->fromArray([
  8165.                 $rdv->getId(),
  8166.                 $dateRdv->format('d/m/Y H:i'),
  8167.                 $joursEcoules ' jours',
  8168.                 $etat $etat->getLibelle() : 'Non défini',
  8169.                 $client $client->getName() . ' ' $client->getLastname() : '',
  8170.                 $client $client->getPhone() : '',
  8171.                 $client && $client->getClientStatus() ? $client->getClientStatus()->getLibelle() : 'Non défini',
  8172.                 $centre $centre->getName() : '',
  8173.                 $centre $centre->getPhone() : '',
  8174.                 $centre $centre->getAddress() . ', ' $centre->getPostale() . ' ' $centre->getCity() : '',
  8175.                 $rdv->getIdAudio() ? $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastname() : '',
  8176.             ], null'A' $row);
  8177.             $row++;
  8178.         }
  8179.         $writer = new Xlsx($spreadsheet);
  8180.         $filename "rdvs-$startDate-to-$endDate.xlsx";
  8181.         // Stream the file to browser
  8182.         $response = new \Symfony\Component\HttpFoundation\StreamedResponse(function () use ($writer) {
  8183.             $writer->save('php://output');
  8184.         });
  8185.         $dispositionHeader $response->headers->makeDisposition(
  8186.             \Symfony\Component\HttpFoundation\ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  8187.             $filename
  8188.         );
  8189.         $response->headers->set('Content-Type''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  8190.         $response->headers->set('Content-Disposition'$dispositionHeader);
  8191.         return $response;
  8192.     }
  8193.     /**
  8194.      * 
  8195.      * @Route("/optical/rdv/export/excel/{startDate}/{endDate}", name="optical_rdv_export_excel", methods={"GET"})
  8196.      */
  8197.     public function exportOpticalExcelFromDate(string $startDatestring $endDate): Response
  8198.     {
  8199.         $start = new \DateTimeImmutable($startDate);
  8200.         $end = new \DateTimeImmutable($endDate);
  8201.         $rdvs $this->rdvRepository->findOpticalBySinceDateAndMyAudio($start$end);
  8202.         $spreadsheet = new Spreadsheet();
  8203.         $sheet $spreadsheet->getActiveSheet();
  8204.         // Headers
  8205.         $sheet->fromArray([
  8206.             'ID du RDV',
  8207.             'Date du RDV',
  8208.             'Jours écoulés',
  8209.             'Statut RDV',
  8210.             'Nom patient',
  8211.             'Téléphone patient',
  8212.             'Statut patient',
  8213.             'Centre',
  8214.             'Téléphone Centre',
  8215.             'Adresse',
  8216.             'Nom Audio'
  8217.         ], null'A1');
  8218.         $today = new \DateTimeImmutable();
  8219.         $row 2;
  8220.         foreach ($rdvs as $rdv) {
  8221.             $dateRdv $rdv->getDate();
  8222.             $joursEcoules $dateRdv->diff($today)->days;
  8223.             $client $rdv->getIdClient();
  8224.             $centre $rdv->getIdCentre();
  8225.             $etat $rdv->getIdEtat();
  8226.             $sheet->fromArray([
  8227.                 $rdv->getId(),
  8228.                 $dateRdv->format('d/m/Y H:i'),
  8229.                 $joursEcoules ' jours',
  8230.                 $etat $etat->getLibelle() : 'Non défini',
  8231.                 $client $client->getName() . ' ' $client->getLastname() : '',
  8232.                 $client $client->getPhone() : '',
  8233.                 $client && $client->getClientStatus() ? $client->getClientStatus()->getLibelle() : 'Non défini',
  8234.                 $centre $centre->getName() : '',
  8235.                 $centre $centre->getPhone() : '',
  8236.                 $centre $centre->getAddress() . ', ' $centre->getPostale() . ' ' $centre->getCity() : '',
  8237.                 $rdv->getIdAudio() ? $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastname() : '',
  8238.             ], null'A' $row);
  8239.             $row++;
  8240.         }
  8241.         $writer = new Xlsx($spreadsheet);
  8242.         $filename "rdvs-$startDate-to-$endDate.xlsx";
  8243.         // Stream the file to browser
  8244.         $response = new \Symfony\Component\HttpFoundation\StreamedResponse(function () use ($writer) {
  8245.             $writer->save('php://output');
  8246.         });
  8247.         $dispositionHeader $response->headers->makeDisposition(
  8248.             \Symfony\Component\HttpFoundation\ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  8249.             $filename
  8250.         );
  8251.         $response->headers->set('Content-Type''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  8252.         $response->headers->set('Content-Disposition'$dispositionHeader);
  8253.         return $response;
  8254.     }
  8255.     /**
  8256.      * 
  8257.      * @Route("/admin/update-note", name="update_note", methods={"POST"})
  8258.      */
  8259.     public function updateNote(Request $requestEntityManagerInterface $em): JsonResponse
  8260.     {
  8261.         $data json_decode($request->getContent(), true);
  8262.         $id $data['id'] ?? null;
  8263.         $note $data['note'] ?? null;
  8264.         if (!$id || $note === null) {
  8265.             return new JsonResponse(['status' => 'error''message' => 'Invalid data'], 400);
  8266.         }
  8267.         $entity $em->getRepository(Rdv::class)->find($id);
  8268.         if (!$entity) {
  8269.             return new JsonResponse(['status' => 'error''message' => 'Entity not found'], 404);
  8270.         }
  8271.         $entity->setNote($note);
  8272.         $em->flush();
  8273.         return new JsonResponse(['status' => 'success']);
  8274.     }
  8275.     /**
  8276.      * 
  8277.      * @Route("/giuili-admin/edit-rdv/{rdvId}/centre/{centreId}", name="update_admin_rdv", methods={"GET"})
  8278.      */
  8279.     public function showRdvCentre(int $rdvIdCentre $centreId): Response
  8280.     {
  8281.         // dd("tets");
  8282.         $center $centres $this->getDoctrine()
  8283.             ->getRepository(AudioCentre::class)
  8284.             ->findOneBy(['id_centre' => $centreId->getId()]);
  8285.         $audio $center->getIdAudio();
  8286.         $motifs $this->getDoctrine()->getRepository(AudioMotif::class)
  8287.             ->findBy(['id_audio' => $audio'isDeleted' => 0]);
  8288.         return $this->render('easyadmin/rdv/centre_show.html.twig', [
  8289.             'audio' => $audio,
  8290.             'rdvId' => $rdvId,
  8291.             'centreId' => $centreId,
  8292.             'motifs' => $motifs,
  8293.         ]);
  8294.     }
  8295.     
  8296.     /**
  8297.      * 
  8298.      * @Route("/optical-center/edit-rdv/{rdvId}/centre/{centreId}", name="update_optical_rdv", methods={"GET"})
  8299.      */
  8300.     public function showRdvCentreOptical(int $rdvIdCentre $centreId): Response
  8301.     {
  8302.         // dd("tets");
  8303.         $center $centres $this->getDoctrine()
  8304.             ->getRepository(AudioCentre::class)
  8305.             ->findOneBy(['id_centre' => $centreId->getId()]);
  8306.         $audio $center->getIdAudio();
  8307.         $motifs $this->getDoctrine()->getRepository(AudioMotif::class)
  8308.             ->findBy(['id_audio' => $audio'isDeleted' => 0]);
  8309.         return $this->render('easyadmin/rdv/centre_show.html.twig', [
  8310.             'audio' => $audio,
  8311.             'rdvId' => $rdvId,
  8312.             'centreId' => $centreId,
  8313.             'motifs' => $motifs,
  8314.         ]);
  8315.     }
  8316.     /**
  8317.      * @Route("/update-rdv-easyadmin", name="update_rdv_easyadmin", methods={"POST"})
  8318.      */
  8319.     public function updateRdvEasyadmin(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendarRdvSmsService $rdvSms): Response
  8320.     {
  8321.         $data json_decode($request->getContent(), true);
  8322.         $rdv $this->getDoctrine()
  8323.             ->getRepository(Rdv::class)
  8324.             ->find($data["rdv_id"]);
  8325.         $pastDate $rdv->getDate();
  8326.         $entityManager $this->getDoctrine()->getManager();
  8327.         if (isset($data["etat_id"])) {
  8328.             $etat $this->getDoctrine()
  8329.                 ->getRepository(EtatRdv::class)
  8330.                 ->findOneBy(['id' => $data["etat_id"]]);
  8331.             if ($etat == null) {
  8332.                 return new Response(json_encode(([
  8333.                     'message' => 'Error, no etat found at this id',
  8334.                     'path' => 'src/Controller/TrustedUserController.php',
  8335.                     "status" => 400,
  8336.                 ])), 400);
  8337.             }
  8338.             $rdv->setIdEtat($etat);
  8339.         }
  8340.         if (isset($data["audio_id"])) {
  8341.             $audio $this->getDoctrine()
  8342.                 ->getRepository(Audio::class)
  8343.                 ->findOneBy(['id' => $data["audio_id"]]);
  8344.             if ($audio == null) {
  8345.                 return new Response(json_encode(([
  8346.                     'message' => 'Error, no audio found at this id',
  8347.                     'path' => 'src/Controller/TrustedUserController.php',
  8348.                     "status" => 400,
  8349.                 ])), 400);
  8350.             }
  8351.             $rdv->setIdAudio($audio);
  8352.         }
  8353.         if (isset($data["motif_id"])) {
  8354.             $motif $this->getDoctrine()
  8355.                 ->getRepository(Motif::class)
  8356.                 ->find($data["motif_id"]);
  8357.             if ($motif == null) {
  8358.                 return new Response(json_encode(([
  8359.                     'message' => 'Error, no motif found at this id',
  8360.                     'path' => 'src/Controller/TrustedUserController.php',
  8361.                     "status" => 400,
  8362.                 ])), 400);
  8363.             }
  8364.             $rdv->setIdMotif($motif);
  8365.         }
  8366.         if (isset($data["client_id"])) {
  8367.             $client $this->getDoctrine()
  8368.                 ->getRepository(Client::class)
  8369.                 ->findOneBy(['id' => $data["client_id"]]);
  8370.             if ($client == null) {
  8371.                 return new Response(json_encode(([
  8372.                     'message' => 'Error, no client found at this id',
  8373.                     'path' => 'src/Controller/TrustedUserController.php',
  8374.                     "status" => 400,
  8375.                 ])), 400);
  8376.             }
  8377.             $rdv->setIdClient($client);
  8378.         }
  8379.         if (isset($data["date"])) {
  8380.             $data["date"] = str_replace("h"":"$data["date"]);
  8381.             $date \DateTime::createFromFormat("Y-m-d\TH:i"$data["date"]);
  8382.             $audioMotif $this->getDoctrine()
  8383.                 ->getRepository(AudioMotif::class)
  8384.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  8385.             if ($audioMotif == null) {
  8386.                 return new Response(json_encode(([
  8387.                     'message' => 'Error, no motif of this id found at this audio',
  8388.                     'path' => 'src/Controller/RdvController.php',
  8389.                     "status" => 400,
  8390.                 ])), 400);
  8391.             }
  8392.             if ($rdv->getIdAudio()->getIsIndie()) {
  8393.                 if ($rdv->getIdCentre()) {
  8394.                     // regular centre audio indie
  8395.                     /** @var AudioCentre */
  8396.                     $liaison $this->getDoctrine()
  8397.                         ->getRepository(AudioCentre::class)
  8398.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  8399.                     if ($liaison == null) {
  8400.                         return new Response(json_encode(([
  8401.                             'message' => 'Error, audio isnt part of the centre',
  8402.                             'path' => 'src/Controller/RdvController.php',
  8403.                             "status" => 400,
  8404.                         ])), 400);
  8405.                     }
  8406.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  8407.                         return new Response(json_encode(([
  8408.                             'message' => 'Error, no horaire found for this audio',
  8409.                             'path' => 'src/Controller/RdvController.php',
  8410.                             "status" => 400,
  8411.                         ])), 400);
  8412.                     }
  8413.                 } else {
  8414.                     // lieu audio indie
  8415.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  8416.                         return new Response(json_encode(([
  8417.                             'message' => 'Error, no horaire found for this audio',
  8418.                             'path' => 'src/Controller/RdvController.php',
  8419.                             "status" => 400,
  8420.                         ])), 400);
  8421.                     }
  8422.                 }
  8423.             } else {
  8424.                 // regular centre
  8425.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  8426.                     return new Response(json_encode(([
  8427.                         'message' => 'Error, no horaire found for this audio',
  8428.                         'path' => 'src/Controller/RdvController.php',
  8429.                         "status" => 400,
  8430.                     ])), 400);
  8431.                 }
  8432.             }
  8433.             $rdv->setDate($date);
  8434.         }
  8435.         if (isset($data["comment"]) && $token->getIdClient()) {
  8436.             $rdv->setComment($data["comment"]);
  8437.         }
  8438.         if (isset($data["review"]) && $token->getIdClient()) {
  8439.             $rdv->setReview($data["review"]);
  8440.         }
  8441.         if (isset($data["note"])) {
  8442.             $rdv->setNote($data["note"]);
  8443.         }
  8444.         $entityManager->flush();
  8445.         $date $rdv->getDate();
  8446.         $smsDate $date->format('d-m-Y H:i');
  8447.         $oldDate $pastDate->format('d-m-Y H:i');
  8448.         $locale 'fr_FR';
  8449.         $formatter = new IntlDateFormatter(
  8450.             $locale,
  8451.             IntlDateFormatter::FULL,
  8452.             IntlDateFormatter::SHORT,
  8453.             null,
  8454.             IntlDateFormatter::GREGORIAN,
  8455.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  8456.         );
  8457.         $smsDateLongFormat $formatter->format($date);
  8458.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  8459.         $frenchDate ucfirst($frenchDate);
  8460.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  8461.         // notif client
  8462.         if ($rdv->getIdEtat()->getId() != 2) {
  8463.             $params = array(
  8464.                 "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  8465.                 "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  8466.                 "date" => $smsDateLongFormat,
  8467.                 "heure" => substr($smsDate1115),
  8468.                 "motif" => $rdv->getIdMotif()->getTitre(),
  8469.                 "centerName" => $rdv->getIdCentre()->getName(),
  8470.                 "centerAddress" => $rdv->getIdCentre()->getAddress(),
  8471.                 "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  8472.                 "audioMail" => $rdv->getIdAudio()->getMail(),
  8473.                 "centerPhone" => $rdv->getIdCentre()->getPhone(),
  8474.                 "centerCity" => $rdv->getIdCentre()->getCity(),
  8475.                 "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  8476.                 'titre' => 'Votre rendez-vous est modifié pour le',
  8477.                 'frenchDate' => $frenchDate,
  8478.             );
  8479.             $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  8480.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject184);
  8481.             $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.";
  8482.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  8483.         }
  8484.         //     //// == suppression
  8485.         else if ($rdv->getIdEtat()->getId() == 2) {
  8486.             $params = array(
  8487.                 "date" => substr($smsDate010),
  8488.                 "lien" => "{$_ENV['BASE_client']}search",
  8489.                 "heure" => substr($smsDate1115),
  8490.                 "patientName" => $client->getLastName(),
  8491.                 'titre' => 'Votre rendez-vous est annulé :',
  8492.                 'centerName' => $rdv->getIdCentre()->getName(),
  8493.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  8494.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  8495.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  8496.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  8497.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  8498.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  8499.                 'motif' => $rdv->getIdMotif()->getTitre(),
  8500.             );
  8501.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  8502.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject188);
  8503.             if ($data["sms"]) {
  8504.                 $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  8505.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  8506.             }
  8507.         }
  8508.         //notif Audio
  8509.         if ($rdv->getIdEtat()->getId() != 2) {
  8510.             $params = array(
  8511.                 "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  8512.                 "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  8513.                 "date" => substr($smsDate010),
  8514.                 "frenchDate" => $frenchDate,
  8515.                 "heure" => substr($smsDate1115),
  8516.                 'motif' => $rdv->getIdMotif()->getTitre(),
  8517.                 'clientPhone' => $client->getPhone(),
  8518.                 'clientNom' => $client->getLastname(),
  8519.                 'clientPrenom' => $client->getName(),
  8520.                 'clientCivilite' => $client->getCivilite(),
  8521.                 'clientPostal' => $client->getPostal(),
  8522.                 'clientMail' => $client->getMail(),
  8523.                 'centerName' => $rdv->getIdCentre()->getName(),
  8524.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  8525.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  8526.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  8527.                 'idPatient' => $client->getId(),
  8528.                 'proUrl' => "{$_ENV['BASE_logiciel']}",
  8529.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  8530.                 'titre' => 'Votre rendez-vous est modifié pour le :'
  8531.             );
  8532.             $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  8533.             $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  8534.             if ($rdv->getIdAudio()->getModifRdvMail()) {
  8535.                 $subject "🔀 Rendez-vous My Audio modifié du " $frenchDate " à " substr($smsDate1115);
  8536.                 $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject186);
  8537.             }
  8538.             if ($rdv->getIdAudio()->getModifRdvSms()) {
  8539.                 $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.";
  8540.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  8541.             }
  8542.         } else if ($rdv->getIdEtat()->getId() == 2) {
  8543.             $params = array(
  8544.                 "date" => substr($smsDate010),
  8545.                 "lien" => "{$_ENV['BASE_client']}search",
  8546.                 "heure" => substr($smsDate1115),
  8547.                 "patientName" => $client->getLastName(),
  8548.                 'titre' => 'Votre rendez-vous est annulé :',
  8549.                 'centerName' => $rdv->getIdCentre()->getName(),
  8550.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  8551.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  8552.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  8553.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  8554.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  8555.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  8556.                 'motif' => $rdv->getIdMotif()->getTitre(),
  8557.             );
  8558.             $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  8559.             $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  8560.             if ($rdv->getIdAudio()->getModifRdvMail()) {
  8561.                 $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  8562.                 $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject188);
  8563.             }
  8564.             if ($rdv->getIdAudio()->getModifRdvSms()) {
  8565.                 $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.";
  8566.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  8567.             }
  8568.         }
  8569.         /* generate sms notif on update */
  8570.         // update sms notification     
  8571.         $rdvSms->updateRdvSms($rdv);
  8572.         // google calendar update
  8573.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  8574.             ->findBy(array('audio' => $rdv->getIdAudio()));
  8575.         $data['rdv'] = $rdv->getId();
  8576.         $data['motif_id'] = $rdv->getIdMotif();
  8577.         $data['note'] = $rdv->getNote();
  8578.         if ($rdv->getIdClient() !== null) {
  8579.             $data["client_id"] = $rdv->getIdClient()->getId();
  8580.         }
  8581.         if ($rdv->getIdClientTemp() !== null) {
  8582.             $data["client_id_temp"] = $rdv->getIdClientTemp()->getId();
  8583.         }
  8584.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  8585.             ->findBy(array('rdv' => $rdv));
  8586.         foreach ($rdvEvents as $rdvEvent) {
  8587.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  8588.             $googleCalendar->updateEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
  8589.         }
  8590.         return new Response(json_encode(([
  8591.             "id" => $rdv->getId(),
  8592.             "motif_id" => $rdv->getIdMotif()->getId(),
  8593.             "audio_id" => $rdv->getIdAudio()->getId(),
  8594.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  8595.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  8596.             "fullName" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  8597.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  8598.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  8599.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  8600.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  8601.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  8602.             "centre_id" => $rdv->getIdCentre()->getId(),
  8603.             "centerName" => $rdv->getIdCentre()->getName(),
  8604.             "etat_id" => $rdv->getIdEtat()->getId(),
  8605.             "date" => $rdv->getDate(),
  8606.             "comment" => $rdv->getComment(),
  8607.             "note" => $rdv->getNote(),
  8608.             "review" => $rdv->getReview(),
  8609.             "status" => 200,
  8610.         ])));
  8611.     }
  8612.     private function checkRdvReminder($rdv): ?array
  8613.     {
  8614.         $dateRdv $rdv->getDate();
  8615.         $today = new \DateTime();
  8616.         $today->setTime(000);
  8617.         $dateRdv->setTime(000);
  8618.         $intervalDays $today->diff($dateRdv)->days;
  8619.         if ($intervalDays === 1) {
  8620.             $interval "24";
  8621.         } elseif ($intervalDays === 2) {
  8622.             $interval "48";
  8623.         } elseif ($intervalDays === 3) {
  8624.             $interval "72";
  8625.         } elseif ($intervalDays === 4) {
  8626.             $interval "96";
  8627.         } else { // >= 4 jours
  8628.             $interval "92";
  8629.         }
  8630.         $client $rdv->getIdClientTemp() ?: $rdv->getIdClient();
  8631.         $clientId $client $client->getId() : null;
  8632.         $clientName null;
  8633.         if ($client) {
  8634.             $clientName $client->getName() . ' ' $client->getLastName();
  8635.         }
  8636.         $motif $rdv->getIdMotif();
  8637.         $motifTitle $motif $motif->getTitre() : null;
  8638.         $centre $rdv->getIdCentre();
  8639.         $centreName null;
  8640.         if ($centre) {
  8641.             $centreName $centre->getName();
  8642.         }
  8643.         return [
  8644.             'rdvId' => $rdv->getId(),
  8645.             'clientId' => $clientId,
  8646.             'clientName' => $clientName ?? 'N/A',
  8647.             'interval' => $interval,
  8648.             'date' => $rdv->getDate() ? $rdv->getDate()->format('d-m-Y H:i') : null,
  8649.             'motif' => $motifTitle ?? 'N/A',
  8650.             'centreName' => $centreName ?? 'N/A',
  8651.         ];
  8652.     }
  8653. }