src/Controller/RdvController.php line 7140

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use DateTime;
  4. use DateInterval;
  5. use DateTimeZone;
  6. use Dompdf\Dompdf;
  7. use App\Entity\Rdv;
  8. use Dompdf\Options;
  9. use App\Entity\Lieu;
  10. use App\Entity\Audio;
  11. use App\Entity\Motif;
  12. use App\Entity\Referral;
  13. use App\Entity\Token;
  14. use Twig\Environment;
  15. use App\Entity\Centre;
  16. use App\Entity\Client;
  17. use \IntlDateFormatter;
  18. use App\Entity\CallLog;
  19. use App\Entity\EtatRdv;
  20. use App\Entity\LeadRdv;
  21. use App\Entity\Proches;
  22. use App\Entity\LieuTier;
  23. use App\Entity\RdvEvent;
  24. use App\Entity\AudioMotif;
  25. use App\Entity\CentreTier;
  26. use App\Entity\ClientTemp;
  27. use App\Entity\LeadStatus;
  28. use App\Entity\Remplacant;
  29. use App\Entity\TestClient;
  30. use App\Entity\AudioCentre;
  31. use App\Service\SmsHandler;
  32. use App\Entity\AccessCentre;
  33. use App\Entity\ClientStatus;
  34. use Psr\Log\LoggerInterface;
  35. use App\Entity\ClientBlocked;
  36. use App\Entity\CentreMutuelle;
  37. use App\Entity\LieuPrestation;
  38. use App\Entity\AudioSpecialite;
  39. use App\Entity\CallInteraction;
  40. use App\Service\PublicFunction;
  41. use App\Entity\CentrePrestation;
  42. use App\Entity\RegionDepartment;
  43. use App\Repository\RdvRepository;
  44. use Symfony\Component\Mime\Email;
  45. use App\Entity\Device\ClientDevice;
  46. use App\Entity\Notification\RdvSms;
  47. use App\Service\Lead\TwilioService;
  48. use App\Service\Lead\WhatsappService;
  49. use App\Entity\SynchronisationSetting;
  50. use App\Service\Lead\SynthflowService;
  51. use App\Service\Lead\ElevenLabsService;
  52. use Doctrine\ORM\EntityManagerInterface;
  53. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  54. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  55. use Symfony\Contracts\Cache\ItemInterface;
  56. use App\Service\Cosium\ClientCosiumService;
  57. use App\Service\Notification\RdvSmsService;
  58. use App\Entity\SpecificSubscription;
  59. use Symfony\Contracts\Cache\CacheInterface;
  60. use App\Entity\Synchronisation\CosiumCenter;
  61. use App\Service\Lead\AppointmentCallService;
  62. use Symfony\Component\Filesystem\Filesystem;
  63. use Symfony\Component\HttpFoundation\Request;
  64. use Symfony\Component\Mailer\MailerInterface;
  65. use Symfony\Component\HttpFoundation\Response;
  66. use Symfony\Component\Routing\Annotation\Route;
  67. use Doctrine\Common\Collections\ArrayCollection;
  68. use App\EasyAdmin\Controller\DashboardController;
  69. use Symfony\Component\HttpKernel\KernelInterface;
  70. use Symfony\Component\HttpFoundation\JsonResponse;
  71. use App\EasyAdmin\Controller\LeadRdvCrudController;
  72. use App\Service\AdsCompany\RepresentativeCdaService;
  73. use App\Entity\Synchronisation\SynchronisationCosium;
  74. use App\Service\GoogleCalendar\GoogleCalendarService;
  75. use App\EasyAdmin\Controller\RdvMyAudioCrudController;
  76. use App\Service\Notification\EmailNotificationService;
  77. use App\Service\Notification\RdvNotificationService;
  78. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  79. use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGenerator;
  80. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  81. use Symfony\Component\Mercure\PublisherInterface;
  82. use Symfony\Component\Mercure\Update;
  83. use App\Service\Mercure\MercureService;
  84. class RdvController extends AbstractController
  85. {
  86.     private $emailNotificationService;
  87.     private $clientCosiumService;
  88.     private $rdvRepository;
  89.     private $entityManager;
  90.     private $cache;
  91.     private $mercure;
  92.     private $twig;
  93.     private AdminUrlGenerator $adminUrlGenerator;
  94.     private WhatsappService $whatsapp;
  95.     private LoggerInterface $logger;  // Service de journalisation
  96.     private RdvRepository $rdvRepo;
  97.     private RdvNotificationService $rdvNotificationService;
  98.     public function __construct(CacheInterface $cacheEntityManagerInterface $entityManagerRdvRepository $rdvRepoEmailNotificationService $emailNotificationServiceClientCosiumService $clientCosiumServiceRdvRepository $rdvRepositoryEnvironment $twigAdminUrlGenerator $adminUrlGeneratorWhatsappService $whatsappLoggerInterface $loggerMercureService $mercureRdvNotificationService $rdvNotificationService)
  99.     {
  100.         $this->entityManager $entityManager;
  101.         $this->emailNotificationService $emailNotificationService;
  102.         $this->clientCosiumService $clientCosiumService;
  103.         $this->rdvRepository $rdvRepository;
  104.         $this->cache $cache;
  105.         $this->twig $twig;
  106.         $this->adminUrlGenerator $adminUrlGenerator;
  107.         $this->whatsapp $whatsapp;
  108.         $this->logger $logger;
  109.         $this->rdvRepo $rdvRepo;
  110.         $this->mercure $mercure;
  111.         $this->rdvNotificationService $rdvNotificationService;
  112.     }
  113.     /**
  114.      * @Route("/rdv/{id}", name="deleteRdvByID", methods={"DELETE"})
  115.      */
  116.     public function deleteRdvByID(Request $requestRdv $rdvGoogleCalendarService $googleCalendar)
  117.     {
  118.         if (!$request->query->get('token')) {
  119.             return new Response(json_encode([
  120.                 "message" => "Pas de token n'a été spécifié",
  121.                 "status" => 401,
  122.             ]), 401);
  123.         }
  124.         $entityManager $this->getDoctrine()->getManager();
  125.         /** @var Token */
  126.         $token $this->getDoctrine()
  127.             ->getRepository(Token::class)
  128.             ->findOneBy(['token' => $request->query->get('token')]);
  129.         if (!$token) {
  130.             return new Response(json_encode([
  131.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  132.                 "status" => 404,
  133.             ]), 404);
  134.         }
  135.         // get token age
  136.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  137.         // if the token if older than 7 days
  138.         if ($dateDiff->7) {
  139.             $entityManager->remove($token);
  140.             $entityManager->flush();
  141.             return $this->json([
  142.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  143.                 'path' => 'src/Controller/ClientController.php',
  144.                 "status" => 401,
  145.             ], 401);
  146.         }
  147.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  148.             return new Response(json_encode([
  149.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  150.                 "status" => 404,
  151.             ]), 404);
  152.         }
  153.         $entityManager->remove($rdv);
  154.         $entityManager->flush();
  155.         return new Response(json_encode(([
  156.             'message' => "Rdv has been successfully deleted",
  157.             "status" => 200,
  158.         ])));
  159.     }
  160.     /**
  161.      * @Route("/rdv/{id}", name="getRdvByID", methods={"GET","HEAD"})
  162.      */
  163.     public function getRdvByID(Request $requestRdv $rdvPublicFunction $publicFunction)
  164.     {
  165.         if (!$request->query->get('token')) {
  166.             return new Response(json_encode([
  167.                 "message" => "Pas de token n'a été spécifié",
  168.                 "status" => 401,
  169.             ]), 401);
  170.         }
  171.         $entityManager $this->getDoctrine()->getManager();
  172.         /** @var Token */
  173.         $token $this->getDoctrine()
  174.             ->getRepository(Token::class)
  175.             ->findOneBy(['token' => $request->query->get('token')]);
  176.         if (!$token) {
  177.             return new Response(json_encode([
  178.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  179.                 "status" => 404,
  180.             ]), 404);
  181.         }
  182.         // get token age
  183.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  184.         // if the token if older than 7 days
  185.         if ($dateDiff->7) {
  186.             $entityManager->remove($token);
  187.             $entityManager->flush();
  188.             return $this->json([
  189.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  190.                 'path' => 'src/Controller/ClientController.php',
  191.                 "status" => 401,
  192.             ], 401);
  193.         }
  194.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  195.             return new Response(json_encode([
  196.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  197.                 "status" => 404,
  198.             ]), 404);
  199.         }
  200.         /** @var AudioCentre */
  201.         $liaison $this->getDoctrine()->getRepository(AudioCentre::class)
  202.             ->findOneBy(array('id_audio' => $rdv->getIdAudio(), 'id_centre' => $rdv->getIdCentre(), 'isConfirmed' => true));
  203.         // Motif filter
  204.         /** @var AudioMotif[] */
  205.         $motifs $this->getDoctrine()->getRepository(AudioMotif::class)
  206.             ->findBy(array('id_audio' => $rdv->getIdAudio(), 'id_motif' => $rdv->getIdMotif()));
  207.         $resultMotif = new ArrayCollection();
  208.         foreach ($motifs as $motif) {
  209.             $resultMotif->add([
  210.                 "id" => $motif->getIdMotif()->getId(),
  211.                 "titre" => $motif->getIdMotif()->getTitre(),
  212.                 "consigne" => $motif->getConsigne(),
  213.                 "duration" => $motif->getDuration(),
  214.             ]);
  215.         }
  216.         // Specialities
  217.         /** @var AudioSpecialite[] */
  218.         $specialities $this->getDoctrine()->getRepository(AudioSpecialite::class)
  219.             ->findBy(array('id_audio' => $rdv->getIdAudio()));
  220.         $resultSpeciality = new ArrayCollection();
  221.         foreach ($specialities as $speciality) {
  222.             $resultSpeciality->add([
  223.                 "id" => $speciality->getIdSpecialite()->getId(),
  224.                 "titre" => $speciality->getIdSpecialite()->getLibelle(),
  225.             ]);
  226.         }
  227.         if ($rdv->getIdCentre())
  228.         /** @var AccessCentre*/
  229.         {
  230.             $accessCentre $this->getDoctrine()->getRepository(AccessCentre::class)
  231.                 ->findOneBy(array('id_centre' => $rdv->getIdCentre()));
  232.         } else
  233.         /** @var AccessCentre*/
  234.         {
  235.             $accessCentre $this->getDoctrine()->getRepository(AccessCentre::class)
  236.                 ->findOneBy(array('id_lieu' => $rdv->getIdLieu()));
  237.         }
  238.         if ($rdv->getIdCentre())
  239.         /** @var CentrePrestation[]*/
  240.         {
  241.             $prestations $this->getDoctrine()->getRepository(CentrePrestation::class)
  242.                 ->findBy(array('id_centre' => $liaison->getIdCentre()->getId()));
  243.         } else
  244.         /** @var LieuPrestation[]*/
  245.         {
  246.             $prestations $this->getDoctrine()->getRepository(LieuPrestation::class)
  247.                 ->findBy(array('id_lieu' => $rdv->getIdLieu()));
  248.         }
  249.         $resultPrestation = new ArrayCollection();
  250.         foreach ($prestations as $prestation) {
  251.             $resultPrestation->add([
  252.                 "id" => $prestation->getIdPrestation()->getId(),
  253.                 "titre" => $prestation->getIdPrestation()->getLibelle(),
  254.             ]);
  255.         }
  256.         $mutuelles $this->getDoctrine()->getRepository(CentreMutuelle::class)
  257.             ->findBy(array('id_centre' => $rdv->getIdCentre()));
  258.         $resultMutuelle = new ArrayCollection();
  259.         foreach ($mutuelles as $mutuelle) {
  260.             $resultMutuelle->add([
  261.                 "id" => $mutuelle->getIdMutuelle()->getId(),
  262.                 "titre" => $mutuelle->getIdMutuelle()->getLibelle(),
  263.             ]);
  264.         }
  265.         if ($rdv->getIdCentre())
  266.         /** @var CentreTier[]*/
  267.         {
  268.             $tiers $this->getDoctrine()->getRepository(CentreTier::class)
  269.                 ->findBy(array('id_centre' => $liaison->getIdCentre()->getId()));
  270.         } else
  271.         /** @var LieuTier[]*/
  272.         {
  273.             $tiers $this->getDoctrine()->getRepository(LieuTier::class)
  274.                 ->findBy(array('id_lieu' => $rdv->getIdLieu()));
  275.         }
  276.         $resultTier = new ArrayCollection();
  277.         foreach ($tiers as $tier) {
  278.             $resultTier->add([
  279.                 "id" => $tier->getIdTier()->getId(),
  280.                 "titre" => $tier->getIdTier()->getLibelle(),
  281.             ]);
  282.         }
  283.         $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  284.         /** @var Rdv[] */
  285.         $audioRdvs $this->getDoctrine()->getRepository(Rdv::class)
  286.             ->findAllReviewsAudio($rdv->getIdAudio()->getId());
  287.         /** @var Rdv[] */
  288.         $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  289.             ->findAllReviewsCentre($rdvCentre->getId());
  290.         // Comment
  291.         /** @var Rdv[] */
  292.         $rdvs $this->getDoctrine()->getRepository(Rdv::class)
  293.             ->findBy(array('id_audio' => $rdv->getIdAudio()));
  294.         $comments = [];
  295.         foreach ($rdvs as $rdv)
  296.             if ($rdv->getComment() && $rdv->getReview() && $rdv->getIdClient())
  297.                 array_push($comments, [
  298.                     "id" => $rdv->getIdClient()->getId(),
  299.                     "name" => $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname()[0] . ".",
  300.                     "comment" => $rdv->getComment(),
  301.                     "isMale" => $rdv->getIdClient()->getCivilite() == "Monsieur",
  302.                     "review" => $rdv->getReview(),
  303.                 ]);
  304.         return new Response(json_encode(([
  305.             "id" => $rdv->getId(),
  306.             "motif_id" => $rdv->getIdMotif()->getId(),
  307.             "motif_titre" => $rdv->getIdMotif()->getTitre(),
  308.             "audio_id" => $rdv->getIdAudio()->getId(),
  309.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  310.             "client_id" => $rdv->getIdClient()->getId(),
  311.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  312.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  313.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  314.             "etat_id" => $rdv->getIdEtat()->getId(),
  315.             "date" => $rdv->getDate(),
  316.             "comment" => $rdv->getComment(),
  317.             "review" => $rdv->getReview(),
  318.             "note" => $rdv->getNote(),
  319.             "testclient" => $rdv->getTestClient() ? [
  320.                 "result" => $rdv->getTestClient()->getResultTonal(),
  321.                 "date" => $rdv->getTestClient()->getDate(),
  322.                 "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  323.             ] : null,
  324.             "comments" => $comments,
  325.             "audio" => [
  326.                 "id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : $rdv->getIdAudio()->getId(),
  327.                 "civilite" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getCivilite() : $rdv->getIdAudio()->getCivilite(),
  328.                 "name" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getName() : $rdv->getIdAudio()->getName(),
  329.                 "lastname" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getLastname() : $rdv->getIdAudio()->getLastname(),
  330.                 "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  331.                 "mail" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getMail() : $rdv->getIdAudio()->getMail(),
  332.                 "phone" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getPhone() : $rdv->getIdAudio()->getPhone(),
  333.                 "adeli" => $rdv->getIdAudio()->getAdeli(),
  334.                 "pin" => $rdv->getIdAudio()->getPin(),
  335.                 "description" => $rdv->getIdAudio()->getDescription(),
  336.                 "averageRating" => $publicFunction->calculateRating($audioRdvs),
  337.                 "nbrReview" => count($audioRdvs),
  338.                 "motifs" => $resultMotif->toArray(),
  339.                 "specialities" => $resultSpeciality->toArray(),
  340.             ],
  341.             "centre" => [
  342.                 "id" => $rdvCentre->getId(),
  343.                 "audio_id" => $rdvCentre->getIdGerant()->getId(),
  344.                 "name" => $rdvCentre->getName(),
  345.                 "imgUrl" => $rdvCentre->getImgUrl(),
  346.                 "isRdvDomicile" => $rdv->getIdCentre() ? $rdvCentre->getIsRdvDomicile() : $rdv->getIdAudio()->getIsRdvDomicileIndie(),
  347.                 "address" => $rdvCentre->getAddress(),
  348.                 "postale" => $rdvCentre->getPostale(),
  349.                 "city" => $rdvCentre->getCity(),
  350.                 "finess" => $rdvCentre->getFiness(),
  351.                 "siret" => $rdvCentre->getSiret(),
  352.                 "website" => $rdvCentre->getWebsite(),
  353.                 "phone" => $rdvCentre->getPhone(),
  354.                 "isHandicap" => $rdvCentre->getIsHandicap(),
  355.                 "longitude" => $rdvCentre->getLongitude(),
  356.                 "latitude" => $rdvCentre->getLatitude(),
  357.                 "averageRating" => $publicFunction->calculateRating($centreRdvs),
  358.                 "nbrReview" => count($centreRdvs),
  359.                 "tram" => $accessCentre->getTram(),
  360.                 "rer" => $accessCentre->getRer(),
  361.                 "metro" => $accessCentre->getMetro(),
  362.                 "bus" => $accessCentre->getBus(),
  363.                 "parking" => $accessCentre->getParkingPublic(),
  364.                 "description" => $rdv->getIdCentre()->getDescription(),
  365.                 "parkingPrivate" => $accessCentre->getParkingPrivate(),
  366.                 "other" => $accessCentre->getOther(),
  367.                 "prestations" => $resultPrestation->toArray(),
  368.                 "mutuelles" => $resultMutuelle->toArray(),
  369.                 "tiers" => $resultTier->toArray(),
  370.                 "isLieu" => false,
  371.                 "schedule" => $rdv->getIdAudio()->getIsIndie() == false $rdv->getIdCentre()->getHoraire() : ($rdv->getIdLieu() ? $rdv->getIdLieu()->getHoraire() : $liaison->getHoraire()),
  372.             ],
  373.             "status" => 200,
  374.         ])));
  375.     }
  376.     /**
  377.      * @Route("/rdvs/client/{id}", name="getRdvsByClientID", methods={"GET","HEAD"})
  378.      */
  379.     public function getRdvsByClientID(Request $requestClient $clientPublicFunction $publicFunction)
  380.     {
  381.         if (!$request->query->get('token')) {
  382.             return new Response(json_encode([
  383.                 "message" => "Pas de token n'a été spécifié",
  384.                 "status" => 401,
  385.             ]), 401);
  386.         }
  387.         $entityManager $this->getDoctrine()->getManager();
  388.         /** @var Token */
  389.         $token $this->getDoctrine()
  390.             ->getRepository(Token::class)
  391.             ->findOneBy(['token' => $request->query->get('token')]);
  392.         if (!$token) {
  393.             return new Response(json_encode([
  394.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  395.                 "status" => 404,
  396.             ]), 404);
  397.         }
  398.         // get token age
  399.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  400.         // if the token if older than 7 days
  401.         if ($dateDiff->7) {
  402.             $entityManager->remove($token);
  403.             $entityManager->flush();
  404.             return $this->json([
  405.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  406.                 'path' => 'src/Controller/ClientController.php',
  407.                 "status" => 401,
  408.             ], 401);
  409.         }
  410.         if ($token->getIdClient()) {
  411.             if ($client != $token->getIdClient()) {
  412.                 return new Response(json_encode([
  413.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  414.                     "status" => 404,
  415.                 ]), 404);
  416.             }
  417.         } else if ($token->getIdAudio()) {
  418.             /** @var Token */
  419.             $token $this->getDoctrine()
  420.                 ->getRepository(Rdv::class)
  421.                 ->findOneBy(['id_client' => $client'id_audio' => $token->getIdAudio()]);
  422.             if ($client != $token->getIdClient()) {
  423.                 return new Response(json_encode([
  424.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  425.                     "status" => 404,
  426.                 ]), 404);
  427.             }
  428.         } else {
  429.             return new Response(json_encode([
  430.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  431.                 "status" => 404,
  432.             ]), 404);
  433.         }
  434.         if ($request->query->get('audio')) {
  435.             /** @var Rdv[] */
  436.             $rdvs $this->getDoctrine()
  437.                 ->getRepository(Rdv::class)
  438.                 ->findBy(['id_client' => $client->getId(), 'id_audio' => $token->getIdAudio()]);
  439.             $rdvResult = new ArrayCollection();
  440.         } else {
  441.             /** @var Rdv[] */
  442.             $rdvs $this->getDoctrine()
  443.                 ->getRepository(Rdv::class)
  444.                 ->findBy(['id_client' => $client->getId()]);
  445.             $rdvResult = new ArrayCollection();
  446.         }
  447.         if ($request->query->get('old')) {
  448.             $oldRdvResult = new ArrayCollection();
  449.         }
  450.         foreach ($rdvs as $rdv) {
  451.             if ($rdv->getIdEtat()->getId() != 1) {
  452.                 continue;
  453.             }
  454.             /** @var AudioMotif */
  455.             $audioMotif $this->getDoctrine()
  456.                 ->getRepository(AudioMotif::class)
  457.                 ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  458.             if (!$audioMotif) {
  459.                 continue;
  460.             }
  461.             $duration '';
  462.             if (is_null($rdv->getDuration())) {
  463.                 $duration $audioMotif->getDuration();
  464.             } else {
  465.                 $duration $rdv->getDuration();
  466.             }
  467.             $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  468.             /** @var Rdv[] */
  469.             $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  470.                 ->findAllReviewsCentre($rdvCentre->getId());
  471.             $rdvItem = [
  472.                 "id" => $rdv->getId(),
  473.                 "motif_id" => $rdv->getIdMotif()->getId(),
  474.                 "duration" => $duration,
  475.                 "color" => $audioMotif->getColor(),
  476.                 "audio_id" => $rdv->getIdAudio()->getId(),
  477.                 "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  478.                 "audio_name" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getName() . " " $rdv->getRemplacant()->getLastname() : $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  479.                 "client_id" => $rdv->getIdClient()->getId(),
  480.                 "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() . " " $rdv->getIdProche()->getLastname() : $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname(),
  481.                 "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  482.                 "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  483.                 "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  484.                 "testclient" => $rdv->getTestClient() ? [
  485.                     "result" => $rdv->getTestClient()->getResultTonal(),
  486.                     "date" => $rdv->getTestClient()->getDate(),
  487.                     "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  488.                 ] : null,
  489.                 "name" => $rdvCentre->getName(),
  490.                 "phone" => $rdvCentre->getPhone(),
  491.                 "imgUrl" => $rdvCentre->getImgUrl(),
  492.                 "address" => $rdvCentre->getAddress(),
  493.                 "postale" => $rdvCentre->getPostale(),
  494.                 "city" => $rdvCentre->getCity(),
  495.                 "etat_id" => $rdvCentre->getId(),
  496.                 "averageRating" => $publicFunction->calculateRating($centreRdvs),
  497.                 "nbrReview" => count($centreRdvs),
  498.                 "acceptedCurrency" => "CB Chèque",
  499.                 "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  500.                 "note" => $rdv->getNote(),
  501.                 "comment" => $rdv->getComment(),
  502.                 "review" => $rdv->getReview(),
  503.             ];
  504.             if ($rdv->getDate() >= new DateTime()) {
  505.                 $rdvResult->add($rdvItem);
  506.             } else if ($request->query->get('old')) {
  507.                 $oldRdvResult->add($rdvItem);
  508.             }
  509.         }
  510.         if ($request->query->get('old')) {
  511.             if ($request->query->get('onlyOld')) {
  512.                 if (count($rdvResult) > || count($oldRdvResult) > 0) {
  513.                     return new Response(json_encode(([
  514.                         "oldRdv" => $oldRdvResult->toArray(),
  515.                         "status" => 200,
  516.                     ])));
  517.                 } else {
  518.                     return new Response(json_encode(([
  519.                         "message" => "Aucun rendez-vous n'a été trouvé!",
  520.                         "test" => "count:" count($rdvs),
  521.                         'path' => 'src/Controller/RdvController.php',
  522.                         "rdv" => array(),
  523.                         "oldRdv" => array(),
  524.                         "status" => 404,
  525.                     ])));
  526.                 }
  527.             } else {
  528.                 if (count($rdvResult) > || count($oldRdvResult) > 0) {
  529.                     return new Response(json_encode(([
  530.                         "rdv" => $rdvResult->toArray(),
  531.                         "oldRdv" => $oldRdvResult->toArray(),
  532.                         "status" => 200,
  533.                     ])));
  534.                 } else {
  535.                     return new Response(json_encode(([
  536.                         "message" => "Aucun rendez-vous n'a été trouvé!",
  537.                         "test" => "count:" count($rdvs),
  538.                         'path' => 'src/Controller/RdvController.php',
  539.                         "rdv" => array(),
  540.                         "oldRdv" => array(),
  541.                         "status" => 404,
  542.                     ])));
  543.                 }
  544.             }
  545.         } else {
  546.             if (count($rdvResult) > 0) {
  547.                 return new Response(json_encode(([
  548.                     "content" => $rdvResult->toArray(),
  549.                     "status" => 200,
  550.                 ])));
  551.             } else {
  552.                 return new Response(json_encode(([
  553.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  554.                     "test" => "count2:" count($rdvs),
  555.                     'path' => 'src/Controller/RdvController.php',
  556.                     "status" => 404,
  557.                 ])));
  558.             }
  559.         }
  560.     }
  561.     /**
  562.      * @Route("/rdvs/client/{id}/centre", name="getRdvsByClientIDForCentre", methods={"GET","HEAD"})
  563.      */
  564.     public function getRdvsByClientIDForCentre(Request $requestClient $clientPublicFunction $publicFunction)
  565.     {
  566.         if (!$request->query->get('token')) {
  567.             return new Response(json_encode([
  568.                 "message" => "Pas de token n'a été spécifié",
  569.                 "status" => 401,
  570.             ]), 401);
  571.         }
  572.         $entityManager $this->getDoctrine()->getManager();
  573.         /** @var Token */
  574.         $token $this->getDoctrine()
  575.             ->getRepository(Token::class)
  576.             ->findOneBy(['token' => $request->query->get('token')]);
  577.         if (!$token) {
  578.             return new Response(json_encode([
  579.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  580.                 "status" => 404,
  581.             ]), 404);
  582.         }
  583.         $audio $this->getDoctrine()
  584.             ->getRepository(Audio::class)
  585.             ->findOneBy(['id' => $request->query->get('audio')]);
  586.         $audioCentre $this->getDoctrine()
  587.             ->getRepository(AudioCentre::class)
  588.             ->findOneBy(['id_audio' => $audio]);
  589.         // get token age
  590.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  591.         // if the token if older than 7 days
  592.         if ($dateDiff->7) {
  593.             $entityManager->remove($token);
  594.             $entityManager->flush();
  595.             return $this->json([
  596.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  597.                 'path' => 'src/Controller/ClientController.php',
  598.                 "status" => 401,
  599.             ], 401);
  600.         }
  601.         if ($token->getIdClient()) {
  602.             if ($client != $token->getIdClient()) {
  603.                 return new Response(json_encode([
  604.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  605.                     "status" => 404,
  606.                 ]), 404);
  607.             }
  608.         } else if ($token->getIdAudio()) {
  609.             /** @var Token */
  610.             if ($token->getIdAudio() != $audio) {
  611.                 return new Response(json_encode([
  612.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  613.                     "status" => 404,
  614.                 ]), 404);
  615.             }
  616.         } else {
  617.             return new Response(json_encode([
  618.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  619.                 "status" => 404,
  620.             ]), 404);
  621.         }
  622.         if ($request->query->get('centre')) {
  623.             /** @var Rdv[] */
  624.             $rdvs $this->getDoctrine()
  625.                 ->getRepository(Rdv::class)
  626.                 ->findBy(['id_client' => $client->getId(), 'id_centre' => $audioCentre->getIdCentre()]);
  627.             $rdvResult = new ArrayCollection();
  628.         } else {
  629.             /** @var Rdv[] */
  630.             $rdvs $this->getDoctrine()
  631.                 ->getRepository(Rdv::class)
  632.                 ->findBy(['id_client' => $client->getId()]);
  633.             $rdvResult = new ArrayCollection();
  634.         }
  635.         if ($request->query->get('old')) {
  636.             $oldRdvResult = new ArrayCollection();
  637.         }
  638.         foreach ($rdvs as $rdv) {
  639.             /*if ($rdv->getIdEtat()->getId() != 1) {
  640.                 continue;
  641.             }*/
  642.             /** @var AudioMotif */
  643.             $audioMotif $this->getDoctrine()
  644.                 ->getRepository(AudioMotif::class)
  645.                 ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  646.             if (!$audioMotif) {
  647.                 continue;
  648.             }
  649.             $duration '';
  650.             if (is_null($rdv->getDuration())) {
  651.                 $duration $audioMotif->getDuration();
  652.             } else {
  653.                 $duration $rdv->getDuration();
  654.             }
  655.             $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  656.             /** @var Rdv[] */
  657.             $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  658.                 ->findAllReviewsCentre($rdvCentre->getId());
  659.             $rdvItem = [
  660.                 "id" => $rdv->getId(),
  661.                 "motif_id" => $rdv->getIdMotif()->getId(),
  662.                 "duration" => $duration,
  663.                 "color" => $audioMotif->getColor(),
  664.                 "audio_id" => $rdv->getIdAudio()->getId(),
  665.                 "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  666.                 "audio_name" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getName() . " " $rdv->getRemplacant()->getLastname() : $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  667.                 "client_id" => $rdv->getIdClient()->getId(),
  668.                 "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() . " " $rdv->getIdProche()->getLastname() : $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname(),
  669.                 "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  670.                 "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  671.                 "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  672.                 "testclient" => $rdv->getTestClient() ? [
  673.                     "result" => $rdv->getTestClient()->getResultTonal(),
  674.                     "date" => $rdv->getTestClient()->getDate(),
  675.                     "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  676.                 ] : null,
  677.                 "name" => $rdvCentre->getName(),
  678.                 "phone" => $rdvCentre->getPhone(),
  679.                 "imgUrl" => $rdvCentre->getImgUrl(),
  680.                 "address" => $rdvCentre->getAddress(),
  681.                 "postale" => $rdvCentre->getPostale(),
  682.                 "city" => $rdvCentre->getCity(),
  683.                 "etat_id" => $rdvCentre->getId(),
  684.                 "averageRating" => $publicFunction->calculateRating($centreRdvs),
  685.                 "nbrReview" => count($centreRdvs),
  686.                 "acceptedCurrency" => "CB Chèque",
  687.                 "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  688.                 "note" => $rdv->getNote(),
  689.                 "comment" => $rdv->getComment(),
  690.                 "review" => $rdv->getReview(),
  691.                 "status" => $rdv->getIdEtat()->getLibelle()
  692.             ];
  693.             // dd(new DateTime());
  694.             if ($rdv->getDate() >= new DateTime()) {
  695.                 $rdvResult->add($rdvItem);
  696.             } else if ($request->query->get('old')) {
  697.                 $oldRdvResult->add($rdvItem);
  698.             }
  699.         }
  700.         if ($request->query->get('old')) {
  701.             if (count($rdvResult) > || count($oldRdvResult) > 0) {
  702.                 return new Response(json_encode(([
  703.                     "rdv" => $rdvResult->toArray(),
  704.                     "oldRdv" => $oldRdvResult->toArray(),
  705.                     "status" => 200,
  706.                 ])));
  707.             } else {
  708.                 return new Response(json_encode(([
  709.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  710.                     "test" => "count:" count($rdvs),
  711.                     'path' => 'src/Controller/RdvController.php',
  712.                     "status" => 404,
  713.                 ])), 404);
  714.             }
  715.         } else {
  716.             if (count($rdvResult) > 0) {
  717.                 return new Response(json_encode(([
  718.                     "content" => $rdvResult->toArray(),
  719.                     "status" => 200,
  720.                 ])));
  721.             } else {
  722.                 return new Response(json_encode(([
  723.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  724.                     "test" => "count2:" count($rdvs),
  725.                     'path' => 'src/Controller/RdvController.php',
  726.                     "status" => 404,
  727.                 ])));
  728.             }
  729.         }
  730.     }
  731.     /////// CRON
  732.     /**
  733.      * @Route("/confirmRdvSms", name="confirmRdvSms", methods={"GET","HEAD"})
  734.      */
  735.     public function confirmRdvSms(PublicFunction $publicFunction): Response
  736.     {
  737.         $date = new DateTime();
  738.         $minutes_to_add 30;
  739.         $date->add(new DateInterval('PT' $minutes_to_add 'M'));
  740.         $date->setTimezone(new DateTimeZone('Europe/Paris'));
  741.         $currentDate $date->format('Y-m-d H:i:00');
  742.         $toSend $this->getDoctrine()->getRepository(Rdv::class)
  743.             ->findRdvsIn10Mins($currentDate);
  744.         $entityManager $this->getDoctrine()->getManager();
  745.         $rdvResult = new ArrayCollection();
  746.         foreach ($toSend as $rdv) {
  747.             $date $rdv->getDate();
  748.             // $smsDate = $date->format('d-m-Y H:i');
  749.             //$client = $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  750.             //$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.";
  751.             // // $publicFunction->sendEmail("MyAudio <noreply@myaudio.fr>", $client->getMail(), "My Audio: Testing CRON", "<p>Testing Cron.</p>");
  752.             //$response = $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $client->getPhone(), 4);
  753.             //$another_response = explode(" | ", $response);
  754.             // $idSms = trim($another_response[2]);
  755.             // $rdv->setIdSms($idSms);
  756.             //$entityManager->persist($rdv);
  757.             // $entityManager->flush();
  758.         }
  759.         return new Response(json_encode([
  760.             // "test" => $idSms,
  761.             "currentDate" => $currentDate
  762.         ]));
  763.     }
  764.     /////// CRON 
  765.     /**
  766.      * @Route("/validateRdvSms", name="validateRdvSms", methods={"GET","HEAD"})
  767.      */
  768.     public function validateRdvSms(Request $requestPublicFunction $publicFunction): Response
  769.     {
  770.         $entityManager $this->getDoctrine()->getManager();
  771.         $smsId $_GET['smsID'];
  772.         $message $_GET['message'];
  773.         $callLog $this->getDoctrine()
  774.             ->getRepository(CallLog::class)
  775.             ->findOneBy(['smsId' => $smsId]);
  776.         if ($callLog) {
  777.             $callLog->setAnsweredAt(new \DateTimeImmutable());
  778.             $interaction = new CallInteraction;
  779.             $interaction->setCallLog($callLog);
  780.             try {
  781.                 if ($message == "1") {
  782.                     $interaction->setStep('equipment_status');
  783.                     $interaction->setResponse('réponse_reçue');
  784.                     $interaction->setTimestamp(new \DateTimeImmutable());
  785.                     $interaction->setAdditionalData(['digit' => '1''status' => 'en_essai']);
  786.                     $entityManager->persist($interaction);
  787.                     $sms "Merci pour votre réponse. Nous notons que vous êtes actuellement en période d'essai. Merci et bonne journée avec MyAudio";
  788.                     $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$callLog->getPhoneNumber(), 4);
  789.                 } else if ($message == "2") {
  790.                     $interaction->setStep('equipment_status');
  791.                     $interaction->setResponse('réponse_reçue');
  792.                     $interaction->setTimestamp(new \DateTimeImmutable());
  793.                     $interaction->setAdditionalData(['digit' => '2''status' => 'finalise']);
  794.                     $entityManager->persist($interaction);
  795.                     $sms "Félicitations pour votre appareillage ! Nous sommes ravis que vous ayez finalisé cet achat important. Bonne journée avec My Audio.";
  796.                     $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$callLog->getPhoneNumber(), 4);
  797.                 } else if ($message == "3") {
  798.                     $interaction->setStep('equipment_status');
  799.                     $interaction->setResponse('réponse_reçue');
  800.                     $interaction->setTimestamp(new \DateTimeImmutable());
  801.                     $interaction->setAdditionalData(['digit' => '3''status' => 'abandonne']);
  802.                     $entityManager->persist($interaction);
  803.                     $sms "Nous avons bien noté que vous avez rendu les appareils sans finaliser l'achat. Bonne journée avec My Audio.";
  804.                     $result $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$callLog->getPhoneNumber(), 4);
  805.                     error_log("Résultat envoi SMSSSSSSSSSSSSSSSSSSSSSSSSS: " json_encode($result));
  806.                 } else if ($message == "4") {
  807.                     $interaction->setStep('equipment_status');
  808.                     $interaction->setResponse('réponse_reçue');
  809.                     $interaction->setTimestamp(new \DateTimeImmutable());
  810.                     $interaction->setAdditionalData(['digit' => '4''status' => 'attente_rdv_orl']);
  811.                     $entityManager->persist($interaction);
  812.                     $sms "Nous avons bien noté que vous etes en attente d'un rendez-vous avec un ORL. Bonne journée avec My Audio.";
  813.                     $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$callLog->getPhoneNumber(), 4);
  814.                 } else if ($message == "5") {
  815.                     $interaction->setStep('equipment_status');
  816.                     $interaction->setResponse('réponse_reçue');
  817.                     $interaction->setTimestamp(new \DateTimeImmutable());
  818.                     $interaction->setAdditionalData(['digit' => '5''status' => 'autre']);
  819.                     $entityManager->persist($interaction);
  820.                     $sms "Merci pour votre réponse. Un conseiller My Audio vous contactera dans les prochains jours. Bonne journée.";
  821.                     $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$callLog->getPhoneNumber(), 4);
  822.                 } else {
  823.                     error_log("Message non reconnu: " $message);
  824.                     return new Response(json_encode([
  825.                         "message" => "La réponse spécifiée est incorrecte",
  826.                         "status" => 401,
  827.                         "réponse" => $message,
  828.                     ]), 401);
  829.                 }
  830.                 $entityManager->flush();
  831.                 return new Response(json_encode([
  832.                     "message" => "Réponse traitée avec succès",
  833.                     "status" => 200,
  834.                 ]));
  835.             } catch (\Exception $e) {
  836.                 return new Response(json_encode([
  837.                     "message" => "Erreur lors du traitement de la réponse: " $e->getMessage(),
  838.                     "status" => 500,
  839.                 ]), 500);
  840.             }
  841.         }
  842.         return new Response(json_encode([
  843.             "smsId" => $smsId,
  844.             "message" => $currentDate
  845.         ]));
  846.     }
  847.     /**
  848.      * @Route("/rdvs/old/client/{id}", name="getOldRdvsByClientId", methods={"GET","HEAD"})
  849.      */
  850.     public function getOldRdvsByClientId(Request $requestClient $clientPublicFunction $publicFunction)
  851.     {
  852.         if (!$request->query->get('token')) {
  853.             return new Response(json_encode([
  854.                 "message" => "Pas de token n'a été spécifié",
  855.                 "status" => 401,
  856.             ]), 401);
  857.         }
  858.         $entityManager $this->getDoctrine()->getManager();
  859.         /** @var Token */
  860.         $token $this->getDoctrine()
  861.             ->getRepository(Token::class)
  862.             ->findOneBy(['token' => $request->query->get('token')]);
  863.         if (!$token) {
  864.             return new Response(json_encode([
  865.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  866.                 "status" => 404,
  867.             ]), 404);
  868.         }
  869.         // get token age
  870.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  871.         // if the token if older than 7 days
  872.         if ($dateDiff->7) {
  873.             $entityManager->remove($token);
  874.             $entityManager->flush();
  875.             return $this->json([
  876.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  877.                 'path' => 'src/Controller/ClientController.php',
  878.                 "status" => 401,
  879.             ], 401);
  880.         }
  881.         if ($token->getIdClient()) {
  882.             if ($client != $token->getIdClient()) {
  883.                 return new Response(json_encode([
  884.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  885.                     "status" => 404,
  886.                 ]), 404);
  887.             }
  888.         } else if ($token->getIdAudio()) {
  889.             /** @var Token */
  890.             $token $this->getDoctrine()
  891.                 ->getRepository(Rdv::class)
  892.                 ->findOneBy(['id_client' => $client'id_audio' => $token->getIdAudio()]);
  893.             if ($client != $token->getIdClient()) {
  894.                 return new Response(json_encode([
  895.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  896.                     "status" => 404,
  897.                 ]), 404);
  898.             }
  899.         } else {
  900.             return new Response(json_encode([
  901.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  902.                 "status" => 404,
  903.             ]), 404);
  904.         }
  905.         if ($request->query->get('audio')) {
  906.             /** @var ActivityRepository */
  907.             $activityRepo $this->getDoctrine();
  908.             if ($request->query->get('limit')) {
  909.                 /** @var Rdv[] */
  910.                 $rdvs $activityRepo
  911.                     ->getRepository(Rdv::class)
  912.                     ->findLastsOldRdvsWithLimit($request->query->get('limit'), $client->getId(), $request->query->get('audio'), new DateTime());
  913.                 $rdvResult = new ArrayCollection();
  914.             } else {
  915.                 /** @var Rdv[] */
  916.                 $rdvs $activityRepo
  917.                     ->getRepository(Rdv::class)
  918.                     ->findOldRdvs($client->getId(), $request->query->get('audio'), new DateTime());
  919.                 $rdvResult = new ArrayCollection();
  920.             }
  921.             foreach ($rdvs as $rdv) {
  922.                 /*if ($rdv->getIdEtat()->getId() != 1) {
  923.                     continue;
  924.                 }*/
  925.                 /** @var AudioMotif */
  926.                 $audioMotif $this->getDoctrine()
  927.                     ->getRepository(AudioMotif::class)
  928.                     ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  929.                 if (!$audioMotif) {
  930.                     continue;
  931.                 }
  932.                 $duration '';
  933.                 if (is_null($rdv->getDuration())) {
  934.                     $duration $audioMotif->getDuration();
  935.                 } else {
  936.                     $duration $rdv->getDuration();
  937.                 }
  938.                 $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  939.                 /** @var Rdv[] */
  940.                 $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  941.                     ->findAllReviewsCentre($rdvCentre->getId());
  942.                 $rdvItem = [
  943.                     "id" => $rdv->getId(),
  944.                     "motif_id" => $rdv->getIdMotif()->getId(),
  945.                     "duration" => $duration,
  946.                     "color" => $audioMotif->getColor(),
  947.                     "audio_id" => $rdv->getIdAudio()->getId(),
  948.                     "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  949.                     "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  950.                     "client_id" => $rdv->getIdClient()->getId(),
  951.                     "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() . " " $rdv->getIdProche()->getLastname() : $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname(),
  952.                     "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  953.                     "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  954.                     "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  955.                     "testclient" => $rdv->getTestClient() ? [
  956.                         "result" => $rdv->getTestClient()->getResultTonal(),
  957.                         "date" => $rdv->getTestClient()->getDate(),
  958.                         "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  959.                     ] : null,
  960.                     "name" => $rdvCentre->getName(),
  961.                     "phone" => $rdvCentre->getPhone(),
  962.                     "imgUrl" => $rdvCentre->getImgUrl(),
  963.                     "address" => $rdvCentre->getAddress(),
  964.                     "postale" => $rdvCentre->getPostale(),
  965.                     "city" => $rdvCentre->getCity(),
  966.                     "etat_id" => $rdvCentre->getId(),
  967.                     "averageRating" => $publicFunction->calculateRating($centreRdvs),
  968.                     "nbrReview" => count($centreRdvs),
  969.                     "acceptedCurrency" => "CB Chèque",
  970.                     "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  971.                     "note" => $rdv->getNote(),
  972.                     "comment" => $rdv->getComment(),
  973.                     "review" => $rdv->getReview(),
  974.                 ];
  975.                 $rdvResult->add($rdvItem);
  976.             }
  977.         }
  978.         if (count($rdvResult) > 0) {
  979.             return new Response(json_encode(([
  980.                 "rdv" => $rdvResult->toArray(),
  981.                 "status" => 200,
  982.             ])));
  983.         } else {
  984.             return new Response(json_encode(([
  985.                 "message" => "Aucun rendez-vous a venir!",
  986.                 'path' => 'src/Controller/RdvController.php',
  987.                 "status" => 404,
  988.             ])));
  989.         }
  990.     }
  991.     /**
  992.      * @Route("/rdvs/old/client/{id}/centre", name="getOldRdvsByClientIdForCentre", methods={"GET","HEAD"})
  993.      */
  994.     public function getOldRdvsByClientIdForCentre(Request $requestClient $clientPublicFunction $publicFunction)
  995.     {
  996.         if (!$request->query->get('token')) {
  997.             return new Response(json_encode([
  998.                 "message" => "Pas de token n'a été spécifié",
  999.                 "status" => 401,
  1000.             ]), 401);
  1001.         }
  1002.         $entityManager $this->getDoctrine()->getManager();
  1003.         /** @var Token */
  1004.         $token $this->getDoctrine()
  1005.             ->getRepository(Token::class)
  1006.             ->findOneBy(['token' => $request->query->get('token')]);
  1007.         if (!$token) {
  1008.             return new Response(json_encode([
  1009.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1010.                 "status" => 404,
  1011.             ]), 404);
  1012.         }
  1013.         $audio $this->getDoctrine()
  1014.             ->getRepository(Audio::class)
  1015.             ->findOneBy(['id' => $request->query->get('audio')]);
  1016.         $audioCentre $this->getDoctrine()
  1017.             ->getRepository(AudioCentre::class)
  1018.             ->findOneBy(['id_audio' => $audio]);
  1019.         // get token age
  1020.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1021.         // if the token if older than 7 days
  1022.         if ($dateDiff->7) {
  1023.             $entityManager->remove($token);
  1024.             $entityManager->flush();
  1025.             return $this->json([
  1026.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1027.                 'path' => 'src/Controller/ClientController.php',
  1028.                 "status" => 401,
  1029.             ], 401);
  1030.         }
  1031.         if ($token->getIdClient()) {
  1032.             if ($client != $token->getIdClient()) {
  1033.                 return new Response(json_encode([
  1034.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  1035.                     "status" => 404,
  1036.                 ]), 404);
  1037.             }
  1038.         } else if ($token->getIdAudio()) {
  1039.             /** @var Token */
  1040.             if ($token->getIdAudio() != $audio) {
  1041.                 return new Response(json_encode([
  1042.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  1043.                     "status" => 404,
  1044.                 ]), 404);
  1045.             }
  1046.         } else {
  1047.             return new Response(json_encode([
  1048.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  1049.                 "status" => 404,
  1050.             ]), 404);
  1051.         }
  1052.         if ($request->query->get('audio')) {
  1053.             /** @var ActivityRepository */
  1054.             $activityRepo $this->getDoctrine();
  1055.             if ($request->query->get('limit')) {
  1056.                 /** @var Rdv[] */
  1057.                 $rdvs $activityRepo
  1058.                     ->getRepository(Rdv::class)
  1059.                     ->findLastsOldRdvCentresWithLimit($request->query->get('limit'), $client->getId(), $audioCentre->getIdCentre()->getId(), new DateTime());
  1060.                 $rdvResult = new ArrayCollection();
  1061.             } else {
  1062.                 /** @var Rdv[] */
  1063.                 $rdvs $activityRepo
  1064.                     ->getRepository(Rdv::class)
  1065.                     ->findOldRdvsByCentre($client->getId(), $audioCentre->getIdCentre()->getId(), new DateTime());
  1066.                 $rdvResult = new ArrayCollection();
  1067.             }
  1068.             //dd($rdvs);
  1069.             foreach ($rdvs as $rdv) {
  1070.                 // we comment this becoz it was just the validate , we implment other choice select
  1071.                 /* if ($rdv->getIdEtat()->getId() != 5) {
  1072.                     continue;
  1073.                 }*/
  1074.                 /** @var AudioMotif */
  1075.                 $audioMotif $this->getDoctrine()
  1076.                     ->getRepository(AudioMotif::class)
  1077.                     ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  1078.                 if (!$audioMotif) {
  1079.                     continue;
  1080.                 }
  1081.                 $duration '';
  1082.                 if (is_null($rdv->getDuration())) {
  1083.                     $duration $audioMotif->getDuration();
  1084.                 } else {
  1085.                     $duration $rdv->getDuration();
  1086.                 }
  1087.                 $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  1088.                 /** @var Rdv[] */
  1089.                 $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  1090.                     ->findAllReviewsCentre($rdvCentre->getId());
  1091.                 $rdvItem = [
  1092.                     "id" => $rdv->getId(),
  1093.                     "motif_id" => $rdv->getIdMotif()->getId(),
  1094.                     "duration" => $duration,
  1095.                     "color" => $audioMotif->getColor(),
  1096.                     "audio_id" => $rdv->getIdAudio()->getId(),
  1097.                     "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  1098.                     "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  1099.                     "client_id" => $rdv->getIdClient()->getId(),
  1100.                     "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() . " " $rdv->getIdProche()->getLastname() : $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname(),
  1101.                     "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  1102.                     "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  1103.                     "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  1104.                     "testclient" => $rdv->getTestClient() ? [
  1105.                         "result" => $rdv->getTestClient()->getResultTonal(),
  1106.                         "date" => $rdv->getTestClient()->getDate(),
  1107.                         "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  1108.                     ] : null,
  1109.                     "name" => $rdvCentre->getName(),
  1110.                     "phone" => $rdvCentre->getPhone(),
  1111.                     "imgUrl" => $rdvCentre->getImgUrl(),
  1112.                     "address" => $rdvCentre->getAddress(),
  1113.                     "postale" => $rdvCentre->getPostale(),
  1114.                     "city" => $rdvCentre->getCity(),
  1115.                     "etat_id" => $rdvCentre->getId(),
  1116.                     "averageRating" => $publicFunction->calculateRating($centreRdvs),
  1117.                     "nbrReview" => count($centreRdvs),
  1118.                     "acceptedCurrency" => "CB Chèque",
  1119.                     "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  1120.                     "note" => $rdv->getNote(),
  1121.                     "comment" => $rdv->getComment(),
  1122.                     "review" => $rdv->getReview(),
  1123.                     "status" => $rdv->getIdEtat()->getLibelle()
  1124.                 ];
  1125.                 $rdvResult->add($rdvItem);
  1126.             }
  1127.         }
  1128.         if (count($rdvResult) > 0) {
  1129.             return new Response(json_encode(([
  1130.                 "rdv" => $rdvResult->toArray(),
  1131.                 "status" => 200,
  1132.             ])));
  1133.         } else {
  1134.             return new Response(json_encode(([
  1135.                 "message" => "Aucun rendez-vous n'a été trouvé!",
  1136.                 'path' => 'src/Controller/RdvController.php',
  1137.                 "status" => 404,
  1138.             ])));
  1139.         }
  1140.     }
  1141.     private function getOpeningHours($centerId)
  1142.     {
  1143.         $center $this->getDoctrine()->getRepository(Centre::class)->find($centerId);
  1144.         $audioCentre $this->getDoctrine()->getRepository(AudioCentre::class)
  1145.             ->findOneBy(['id_centre' => $center->getId(), 'id_audio' => $center->getIdGerant()->getId()]);
  1146.         $schedule $audioCentre->getHoraire();
  1147.         $availableHours = [];
  1148.         if (isset($schedule['fixed'])) {
  1149.             foreach ($schedule['fixed'] as $day => $hours) {
  1150.                 $dayInFrench strtolower($day);
  1151.                 $slots = [];
  1152.                 foreach ($hours as $period) {
  1153.                     $start strtotime($period['open']);
  1154.                     $end strtotime($period['close']);
  1155.                     while ($start $end) {
  1156.                         $slots[] = date('H:i'$start);
  1157.                         $start strtotime('+30 minutes'$start);
  1158.                     }
  1159.                 }
  1160.                 $availableHours[$dayInFrench] = $slots;
  1161.             }
  1162.         }
  1163.         if (isset($schedule['exceptionalOpened'])) {
  1164.             foreach ($schedule['exceptionalOpened'] as $exception) {
  1165.                 $dayOfWeek strtolower(date('l'strtotime($exception['open'])));
  1166.                 $start strtotime($exception['open']);
  1167.                 $end strtotime($exception['close']);
  1168.                 $exceptionSlots = [];
  1169.                 while ($start $end) {
  1170.                     $exceptionSlots[] = date('H:i'$start);
  1171.                     $start strtotime('+30 minutes'$start);
  1172.                 }
  1173.                 $availableHours[$dayOfWeek] = array_merge(
  1174.                     $availableHours[$dayOfWeek] ?? [],
  1175.                     $exceptionSlots
  1176.                 );
  1177.             }
  1178.         }
  1179.         if (isset($schedule['exceptionalClosed'])) {
  1180.             foreach ($schedule['exceptionalClosed'] as $exception) {
  1181.                 $dayOfWeek strtolower(date('l'strtotime($exception['open'])));
  1182.                 unset($availableHours[$dayOfWeek]);
  1183.             }
  1184.         }
  1185.         return $availableHours;
  1186.     }
  1187.     private function getBookedSlotsForDate($centerId$date)
  1188.     {
  1189.         $bookedSlots $this->getDoctrine()
  1190.             ->getRepository(Rdv::class)
  1191.             ->getBookedSlotsForDate($centerId$date);
  1192.         return $bookedSlots;
  1193.     }
  1194.     private function getAvailableSlotsForDate($openingHours$centerId$date)
  1195.     {
  1196.         $dayOfWeek date('l'strtotime($date));
  1197.         $dayInFrench $this->convertDayToFrench($dayOfWeek);
  1198.         if (!$dayInFrench) {
  1199.             throw new \Exception("Invalid day of the week: $dayOfWeek");
  1200.         }
  1201.         $slots $openingHours[$dayInFrench] ?? [];
  1202.         $bookedSlots $this->getBookedSlotsForDate($centerId$date);
  1203.         $bookedTimes = [];
  1204.         foreach ($bookedSlots as $bookedSlot) {
  1205.             $startTime $bookedSlot['date'];
  1206.             $duration $bookedSlot['duration'];
  1207.             $endTime = (clone $startTime)->modify("+$duration minutes");
  1208.             $bookedTimes[] = ['start' => $startTime'end' => $endTime];
  1209.         }
  1210.         $availableSlots = [];
  1211.         foreach ($slots as $slot) {
  1212.             $slotTime \DateTime::createFromFormat('H:i'$slot);
  1213.             $slotTime->setDate(date('Y'strtotime($date)), date('m'strtotime($date)), date('d'strtotime($date)));
  1214.             if (!$slotTime) {
  1215.                 continue;
  1216.             }
  1217.             $isAvailable true;
  1218.             foreach ($bookedTimes as $bookedTime) {
  1219.                 if ($slotTime >= $bookedTime['start'] && $slotTime $bookedTime['end']) {
  1220.                     $isAvailable false;
  1221.                     break;
  1222.                 }
  1223.             }
  1224.             if ($isAvailable) {
  1225.                 $availableSlots[] = $slot;
  1226.             }
  1227.         }
  1228.         return $availableSlots;
  1229.     }
  1230.     private function convertDayToFrench($englishDay)
  1231.     {
  1232.         $daysMap = [
  1233.             'monday' => 'lundi',
  1234.             'tuesday' => 'mardi',
  1235.             'wednesday' => 'mercredi',
  1236.             'thursday' => 'jeudi',
  1237.             'friday' => 'vendredi',
  1238.             'saturday' => 'samedi',
  1239.             'sunday' => 'dimanche'
  1240.         ];
  1241.         return $daysMap[strtolower($englishDay)] ?? null;
  1242.     }
  1243.     /**
  1244.      * @Route("/audio/{id}/rdvs/", name="getAudioRdvs", methods={"GET","HEAD"})
  1245.      */
  1246.     public function getAudioRdvs(Request $requestAudio $audio)
  1247.     {
  1248.         if (!$request->query->get('token')) {
  1249.             return new Response(json_encode([
  1250.                 "message" => "Pas de token n'a été spécifié",
  1251.                 "status" => 401,
  1252.             ]), 401);
  1253.         }
  1254.         $entityManager $this->getDoctrine()->getManager();
  1255.         /** @var Token */
  1256.         $token $this->getDoctrine()
  1257.             ->getRepository(Token::class)
  1258.             ->findOneBy(['token' => $request->query->get('token')]);
  1259.         if (!$token) {
  1260.             return new Response(json_encode([
  1261.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1262.                 "status" => 404,
  1263.             ]), 404);
  1264.         }
  1265.         // get token age
  1266.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1267.         // if the token if older than 7 days
  1268.         if ($dateDiff->7) {
  1269.             $entityManager->remove($token);
  1270.             $entityManager->flush();
  1271.             return $this->json([
  1272.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1273.                 'path' => 'src/Controller/ClientController.php',
  1274.                 "status" => 401,
  1275.             ], 401);
  1276.         }
  1277.         if ($audio != $token->getIdAudio()) {
  1278.             return new Response(json_encode([
  1279.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  1280.                 "status" => 404,
  1281.             ]), 404);
  1282.         }
  1283.         $centre = (int)$request->query->get('centre');
  1284.         if (($request->query->get('debut')) && ($request->query->get('fin'))) {
  1285.             $rdvs $this->getDoctrine()
  1286.                 ->getRepository(Rdv::class)
  1287.                 ->findBetweenDate(
  1288.                     $audio->getId(),
  1289.                     new DateTime($request->query->get('debut')),
  1290.                     new DateTime($request->query->get('fin')),
  1291.                     $centre // Le centre est maintenant un entier
  1292.                 );
  1293.         } else {
  1294.             $rdvs $this->getDoctrine()
  1295.                 ->getRepository(Rdv::class)
  1296.                 ->findBy(['id_audio' => $audio->getId()]);
  1297.         }
  1298.         $rdvResult = new ArrayCollection();
  1299.         $centerId $request->query->get('centre');
  1300.         // $openingHours = $this->getOpeningHours($centerId); 
  1301.         $centerId $request->query->get('centre');
  1302.         $dateCache = new \DateTime();
  1303.         $openingHours $this->cache->get('centre_' $centerId '_horaires_' $dateCache->format('Y-m-d'), function (ItemInterface $item) use ($centerId$dateCache) {
  1304.             $item->expiresAfter(7200);
  1305.             return $this->getOpeningHours($centerId);
  1306.         });
  1307.         //dd($openingHours);
  1308.         foreach ($rdvs as $rdv) {
  1309.             if ($rdv->getIdEtat()->getId() != null) {
  1310.                 if ($rdv->getIsAbsence() != 1) {
  1311.                     /** @var AudioMotif */
  1312.                     $audioMotif $this->getDoctrine()
  1313.                         ->getRepository(AudioMotif::class)
  1314.                         ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $audio->getId()]);
  1315.                     if (!isset($audioMotif)) {
  1316.                         continue;
  1317.                     }
  1318.                     $motif $this->getDoctrine()
  1319.                         ->getRepository(Motif::class)
  1320.                         ->findOneBy(['id' => $rdv->getIdMotif()->getId()]);
  1321.                     $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  1322.                     if ($rdv->getIdClientTemp()) {
  1323.                         $confiance "";
  1324.                     } else {
  1325.                         $confiance $client->getIdPersonneConfiance() ? $client->getIdPersonneConfiance()->getId() : null;
  1326.                     }
  1327.                 }
  1328.                 $duration '';
  1329.                 if (is_null($rdv->getDuration())) {
  1330.                     $duration $audioMotif->getDuration();
  1331.                 } else {
  1332.                     $duration $rdv->getDuration();
  1333.                 }
  1334.                 $dateFin = new DateTime($rdv->getDate()->format('Y-m-d\TH:i:s'));
  1335.                 $dateFin $dateFin->add(new DateInterval("PT" $duration "M"));
  1336.                 if ($rdv->getIdClientTemp()) {
  1337.                     $findNextRdv $this->getDoctrine()
  1338.                         ->getRepository(Rdv::class)
  1339.                         ->findBy([
  1340.                             "id_client_temp" => $rdv->getIdClientTemp(),
  1341.                             "id_motif" => ['106''107''108''109']
  1342.                         ]);
  1343.                 } else {
  1344.                     $findNextRdv $this->getDoctrine()
  1345.                         ->getRepository(Rdv::class)
  1346.                         ->findBy([
  1347.                             "id_client_temp" => $rdv->getIdClient(),
  1348.                             "id_motif" => ['106''107''108''109']
  1349.                         ]);
  1350.                 }
  1351.                 $finalRdv null;
  1352.                 /*if ($rdv->getRdvParent()) {
  1353.     $finalRdv = $this->getDoctrine()
  1354.         ->getRepository(Rdv::class)
  1355.         ->find($rdv->getRdvParent());
  1356. }*/
  1357.                 //if($client->getClientDevices())
  1358.                 //{
  1359.                 //if ($client->getClientDevices()->first()) {
  1360.                 /*$nextRdv = $this->getDoctrine()
  1361.                  ->getRepository(Rdv::class)
  1362.                  ->find($finalRdv->getClientDevice()->getRdv()->getId());*/
  1363.                 //  }
  1364.                 //}
  1365.                 if ($rdv->getIsAbsence() != 1) {
  1366.                     if ($rdv->getIdClientTemp()) {
  1367.                         $nextRdvs $this->getDoctrine()
  1368.                             ->getRepository(Rdv::class)
  1369.                             ->findBy([
  1370.                                 "id_client_temp" => $client,
  1371.                                 "id_motif" => ['106''107''108''109']
  1372.                             ]);
  1373.                     } else {
  1374.                         $nextRdvs $this->getDoctrine()
  1375.                             ->getRepository(Rdv::class)
  1376.                             ->findBy([
  1377.                                 "id_client" => $client,
  1378.                                 "id_motif" => ['106''107''108''109']
  1379.                             ]);
  1380.                     }
  1381.                     if ($client->getClientDevices()) {
  1382.                         if ($client->getClientDevices()->first()) {
  1383.                             if (empty($nextRdvs)) {
  1384.                                 $isNextRdv false;
  1385.                                 $initialRdvDate $rdv->getDate();
  1386.                                 $availableSlots = [
  1387.                                     'Suivi de l’essai' => $this->findFirstAvailableSlot($centerId$initialRdvDate7),
  1388.                                     'Confirmation de l’essai' => $this->findFirstAvailableSlot($centerId$initialRdvDate14),
  1389.                                     'Validation de l’appareillage' => $this->findFirstAvailableSlot($centerId$initialRdvDate21),
  1390.                                     'Facturation de l’appareillage' => $this->findFirstAvailableSlot($centerId$initialRdvDate30),
  1391.                                     'duration' => "30"
  1392.                                 ];
  1393.                                 $mappedNextRdvs = [
  1394.                                     'Suivi de l’essai' => $this->findAvailableDay($centerId$initialRdvDate7),
  1395.                                     'Confirmation de l’essai' => $this->findAvailableDay($centerId$initialRdvDate14),
  1396.                                     'Validation de l’appareillage' => $this->findAvailableDay($centerId$initialRdvDate21),
  1397.                                     'Facturation de l’appareillage' => $this->findAvailableDay($centerId$initialRdvDate30),
  1398.                                     'duration' => "30"
  1399.                                 ];
  1400.                             } else {
  1401.                                 $isNextRdv true;
  1402.                                 $initialRdvDate $rdv->getDate();
  1403.                                 // Available slots for each follow-up date
  1404.                                 $availableSlots = [];
  1405.                                 if (isset($nextRdvs[0])) {
  1406.                                     $availableSlots['Suivi de l’essai'] = $this->getAvailableSlotsForDate(
  1407.                                         $openingHours,
  1408.                                         $centerId,
  1409.                                         $nextRdvs[0]->getDate()->format('Y-m-d')
  1410.                                     );
  1411.                                 }
  1412.                                 if (isset($nextRdvs[1])) {
  1413.                                     $availableSlots['Confirmation de l’essai'] = $this->getAvailableSlotsForDate(
  1414.                                         $openingHours,
  1415.                                         $centerId,
  1416.                                         $nextRdvs[1]->getDate()->format('Y-m-d')
  1417.                                     );
  1418.                                 }
  1419.                                 if (isset($nextRdvs[2])) {
  1420.                                     $availableSlots['Validation de l’appareillage'] = $this->getAvailableSlotsForDate(
  1421.                                         $openingHours,
  1422.                                         $centerId,
  1423.                                         $nextRdvs[2]->getDate()->format('Y-m-d')
  1424.                                     );
  1425.                                 }
  1426.                                 if (isset($nextRdvs[3])) {
  1427.                                     $availableSlots['Facturation de l’appareillage'] = $this->getAvailableSlotsForDate(
  1428.                                         $openingHours,
  1429.                                         $centerId,
  1430.                                         $nextRdvs[3]->getDate()->format('Y-m-d')
  1431.                                     );
  1432.                                 }
  1433.                                 $mappedNextRdvs array_map(function ($rdv) {
  1434.                                     return [
  1435.                                         'id' => $rdv->getId(),
  1436.                                         'date' => $rdv->getDate()->format('d-m-Y'),
  1437.                                         'hours' => $rdv->getDate()->format('H:i'),
  1438.                                         'duration' => $rdv->getDuration(),
  1439.                                         "motif_id" => $rdv->getIdMotif()->getId(),
  1440.                                         "motif_titre" => $rdv->getIdMotif()->getTitre(),
  1441.                                     ];
  1442.                                 }, $nextRdvs);
  1443.                             }
  1444.                         }
  1445.                     }
  1446.                     $rdvItem = [
  1447.                         "id" => $rdv->getId(),
  1448.                         "motif_id" => $rdv->getIdMotif()->getId(),
  1449.                         "motif_titre" => $motif->getTitre(),
  1450.                         "duration" => $duration,
  1451.                         "color" => $audioMotif->getColor(),
  1452.                         "audio_id" => $rdv->getIdAudio()->getId(),
  1453.                         "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  1454.                         "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  1455.                         "client_id" => $client->getId(),
  1456.                         "isClient" => ($client instanceof Client) ? 0,
  1457.                         "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() : $client->getName(),
  1458.                         "client_lastname" => $rdv->getIdProche() ? $rdv->getIdProche()->getLastname() : $client->getLastname(),
  1459.                         "client_mail" => $client->getMail(),
  1460.                         "client_tel" => $client->getPhone(),
  1461.                         "client_fixe" => $client->getPhoneFixe(),
  1462.                         "confiance" =>  $confiance,
  1463.                         "client_birthday" => $client->getBirthdate() ? $client->getBirthdate()->format("Y-m-d") : null,
  1464.                         "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  1465.                         "centre_id" => $rdv->getIdCentre()->getId(),
  1466.                         "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  1467.                         "testclient" => $rdv->getTestClient() ? [
  1468.                             "result" => $rdv->getTestClient()->getResultTonal(),
  1469.                             "date" => $rdv->getTestClient()->getDate(),
  1470.                             "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  1471.                         ] : null,
  1472.                         "name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : $rdv->getIdLieu()->getName(),
  1473.                         "centerName" => $rdv->getIdCentre()->getName(),
  1474.                         "phone" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getPhone() : $rdv->getIdLieu()->getPhone(),
  1475.                         "etat_id" => $rdv->getIdEtat()->getId(),
  1476.                         "clientEtatId" => $client->getClientStatus() ? $client->getClientStatus()->getId() : 0,
  1477.                         "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  1478.                         "dateFin" => $dateFin->format('Y-m-d\TH:i:s'),
  1479.                         "comment" => $rdv->getComment(),
  1480.                         "note" => $rdv->getNote(),
  1481.                         "isTemp" => $rdv->getIdClientTemp() ? 0,
  1482.                         "isAbsence" => $rdv->getIsAbsence(),
  1483.                         "device" => $client->getClientDevices()->first() ? [
  1484.                             "isDevice" => true,
  1485.                             "isNextRdv" => $isNextRdv,
  1486.                             "deviceID" => $client->getClientDevices()->first()->getDevice()->getId(),
  1487.                             "clientDeviceID" => $client->getClientDevices()->first()->getId(),
  1488.                             "deviceModel" => $client->getClientDevices()->first()->getDevice()->getModel(),
  1489.                             "settingDeviceId" => $client->getClientDevices()->first()->getSettingDevice()->getSlug(),
  1490.                             "settingName" => $client->getClientDevices()->first()->getSettingDevice()->getName(),
  1491.                             "settingSlug" => $client->getClientDevices()->first()->getSettingDevice()->getSlug(),
  1492.                             "nextRdvs" => $mappedNextRdvs,
  1493.                             "available_slots" => $availableSlots
  1494.                         ] : [
  1495.                             "isDevice" => false
  1496.                         ]
  1497.                     ];
  1498.                 } else {
  1499.                     // $clientDevice = $client->getClientDevices()->first();
  1500.                     $rdvItem = [
  1501.                         "id" => $rdv->getId(),
  1502.                         "duration" => $duration,
  1503.                         "color" => $rdv->getColor() ? $rdv->getColor() . '66' '#ffb2b266',
  1504.                         "audio_id" => $rdv->getIdAudio()->getId(),
  1505.                         "client_id" =>  "",
  1506.                         "isClient" => false,
  1507.                         "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  1508.                         "centre_id" => $rdv->getIdCentre()->getId(),
  1509.                         "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  1510.                         "name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : $rdv->getIdLieu()->getName(),
  1511.                         "phone" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getPhone() : $rdv->getIdLieu()->getPhone(),
  1512.                         "etat_id" => $rdv->getIdEtat()->getId(),
  1513.                         "clientEtatId" => "",
  1514.                         "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  1515.                         "dateFin" => $dateFin->format('Y-m-d\TH:i:s'),
  1516.                         "note" => $rdv->getNote(),
  1517.                         "device" => "",
  1518.                         "centerName" => $rdv->getIdCentre()->getName(),
  1519.                         "isTemp" => $rdv->getIdClientTemp() ? 0,
  1520.                         "isAbsence" => $rdv->getIsAbsence(),
  1521.                         "motif_titre" => $rdv->getMotifAbsence() ? $rdv->getMotifAbsence() : "Absence",
  1522.                     ];
  1523.                 }
  1524.                 //  if ($rdv->getDate() >= new DateTime())
  1525.                 $rdvResult->add($rdvItem);
  1526.             }
  1527.         }
  1528.         $startDate = new \DateTime('2024-02-20');
  1529.         $rdvs $this->rdvRepo->findRdvsNeedingReminderByAudio($startDate$audio->getId());
  1530.         //dd($audio->getId());
  1531.         $reminders = [];
  1532.         //dd($rdvs);
  1533.         foreach ($rdvs as $rdv) {
  1534.             $info $this->checkRdvReminder($rdv);
  1535.             if ($info !== null) {
  1536.                 $reminders[] = $info;
  1537.             }
  1538.         }
  1539.         //dd($reminders);
  1540.         if (count($rdvResult) > 0) {
  1541.             return new Response(json_encode(([
  1542.                 "content" => $rdvResult->toArray(),
  1543.                 "status" => 200,
  1544.                 "reminders" => $reminders,
  1545.                 "datefin" => $dateFin
  1546.             ])));
  1547.         } else {
  1548.             $rdvItem = [];
  1549.             //$rdvResult->add($rdvItem);
  1550.             return new Response(json_encode(([
  1551.                 "content" => $rdvResult->toArray(),
  1552.                 "message" => "Aucun rendez-vous n'a été trouvé!",
  1553.                 'path' => 'src/Controller/RdvController.php',
  1554.                 "reminders" => $reminders,
  1555.                 "status" => 404,
  1556.             ])));
  1557.         }
  1558.     }
  1559.     private function findAvailableDay(int $centerId\DateTime $initialRdvDateint $offset): string
  1560.     {
  1561.         $currentDate = (clone $initialRdvDate)->modify("+{$offset} days");
  1562.         while (true) {
  1563.             $formattedDate $currentDate->format('Y-m-d');
  1564.             $slots $this->getAvailableSlotsForDate(
  1565.                 $this->getOpeningHoursList($centerId$formattedDate),
  1566.                 $centerId,
  1567.                 $formattedDate
  1568.             );
  1569.             if (!empty($slots)) {
  1570.                 return $formattedDate;
  1571.             }
  1572.             $currentDate->modify('+1 day');
  1573.         }
  1574.     }
  1575.     private function findFirstAvailableSlot(int $centerId\DateTime $initialRdvDateint $offset): array
  1576.     {
  1577.         $currentDate = (clone $initialRdvDate)->modify("+{$offset} days");
  1578.         while (true) {
  1579.             $formattedDate $currentDate->format('Y-m-d');
  1580.             $slots $this->getAvailableSlotsForDate(
  1581.                 $this->getOpeningHoursList($centerId$formattedDate),
  1582.                 $centerId,
  1583.                 $formattedDate
  1584.             );
  1585.             if (!empty($slots)) {
  1586.                 return $slots;
  1587.             }
  1588.             $currentDate->modify('+1 day');
  1589.         }
  1590.     }
  1591.     private function getOpeningHoursList($centerId$date)
  1592.     {
  1593.         $center $this->getDoctrine()->getRepository(Centre::class)->find($centerId);
  1594.         $audioCentre $this->getDoctrine()->getRepository(AudioCentre::class)
  1595.             ->findOneBy(['id_centre' => $center->getId(), 'id_audio' => $center->getIdGerant()->getId()]);
  1596.         $schedule $audioCentre->getHoraire();
  1597.         $availableHours = [];
  1598.         $holidayDates = [
  1599.             'JourdelAn' => '01-01',
  1600.             'LundidePâques' => '21-04',
  1601.             'FêteduTravail' => '01-05',
  1602.             'Victoire1945' => '08-05',
  1603.             'Ascension' => '29-05',
  1604.             'LundidePentecôte' => '09-06',
  1605.             'FêteNationale' => '14-07',
  1606.             'Assomption' => '15-08',
  1607.             'Toussaint' => '01-11',
  1608.             'Armistice1918' => '11-11',
  1609.             'Noël' => '25-12',
  1610.         ];
  1611.         $holidays $center->getHorairesHoliday();
  1612.         $requestDate date('d-m'strtotime($date));
  1613.         $englishToFrenchDays = [
  1614.             'monday' => 'lundi',
  1615.             'tuesday' => 'mardi',
  1616.             'wednesday' => 'mercredi',
  1617.             'thursday' => 'jeudi',
  1618.             'friday' => 'vendredi',
  1619.             'saturday' => 'samedi',
  1620.             'sunday' => 'dimanche',
  1621.         ];
  1622.         $dayOfWeek strtolower(date('l'strtotime($date)));
  1623.         $dayInFrench $englishToFrenchDays[$dayOfWeek];
  1624.         if (isset($schedule['fixed'])) {
  1625.             foreach ($schedule['fixed'] as $day => $hours) {
  1626.                 $dayKey strtolower($day);
  1627.                 $slots = [];
  1628.                 foreach ($hours as $period) {
  1629.                     $start strtotime($period['open']);
  1630.                     $end strtotime($period['close']);
  1631.                     while ($start $end) {
  1632.                         $slots[] = date('H:i'$start);
  1633.                         $start strtotime('+30 minutes'$start);
  1634.                     }
  1635.                 }
  1636.                 $availableHours[$dayKey] = $slots;
  1637.             }
  1638.         }
  1639.         foreach ($holidays['fixed'] as $holiday => $hours) {
  1640.             if (isset($holidayDates[$holiday]) && $holidayDates[$holiday] === $requestDate) {
  1641.                 $holidaySlots = [];
  1642.                 if (!empty($hours)) {
  1643.                     foreach ($hours as $period) {
  1644.                         $start strtotime($period['open']);
  1645.                         $end strtotime($period['close']);
  1646.                         while ($start $end) {
  1647.                             $holidaySlots[] = date('H:i'$start);
  1648.                             $start strtotime('+30 minutes'$start);
  1649.                         }
  1650.                     }
  1651.                     $availableHours[$dayInFrench] = $holidaySlots;
  1652.                 } else {
  1653.                     $availableHours[$dayInFrench] = [];
  1654.                 }
  1655.                 break;
  1656.             }
  1657.         }
  1658.         return $availableHours;
  1659.     }
  1660.     /**
  1661.      * @Route("/audio/{id}/rdvsTest/", name="getAudioRdvsTest", methods={"GET","HEAD"})
  1662.      */
  1663.     public function getAudioRdvsTest(Request $requestAudio $audio)
  1664.     {
  1665.         if (!$request->query->get('token')) {
  1666.             return new Response(json_encode([
  1667.                 "message" => "Pas de token n'a été spécifié",
  1668.                 "status" => 401,
  1669.             ]), 401);
  1670.         }
  1671.         $entityManager $this->getDoctrine()->getManager();
  1672.         /** @var Token */
  1673.         $token $this->getDoctrine()
  1674.             ->getRepository(Token::class)
  1675.             ->findOneBy(['token' => $request->query->get('token')]);
  1676.         if (!$token) {
  1677.             return new Response(json_encode([
  1678.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1679.                 "status" => 404,
  1680.             ]), 404);
  1681.         }
  1682.         // get token age
  1683.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1684.         // if the token if older than 7 days
  1685.         if ($dateDiff->7) {
  1686.             $entityManager->remove($token);
  1687.             $entityManager->flush();
  1688.             return $this->json([
  1689.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1690.                 'path' => 'src/Controller/ClientController.php',
  1691.                 "status" => 401,
  1692.             ], 401);
  1693.         }
  1694.         if ($audio != $token->getIdAudio()) {
  1695.             return new Response(json_encode([
  1696.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  1697.                 "status" => 404,
  1698.             ]), 404);
  1699.         }
  1700.         /** @var Rdv[] */
  1701.         if (($request->query->get('debut')) && ($request->query->get('fin'))) {
  1702.             $rdvs $this->getDoctrine()
  1703.                 ->getRepository(Rdv::class)
  1704.                 ->findBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1705.         } else {
  1706.             $rdvs $this->getDoctrine()
  1707.                 ->getRepository(Rdv::class)
  1708.                 ->findBy(['id_audio' => $audio->getId()]);
  1709.         }
  1710.         $rdvResult = new ArrayCollection();
  1711.         foreach ($rdvs as $rdv) {
  1712.             if ($rdv->getIdEtat()->getId() != null) {
  1713.                 /** @var AudioMotif */
  1714.                 $audioMotif $this->getDoctrine()
  1715.                     ->getRepository(AudioMotif::class)
  1716.                     ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $audio->getId()]);
  1717.                 if (!isset($audioMotif)) {
  1718.                     continue;
  1719.                 }
  1720.                 $motif $this->getDoctrine()
  1721.                     ->getRepository(Motif::class)
  1722.                     ->findOneBy(['id' => $rdv->getIdMotif()->getId()]);
  1723.                 $dateFin = new DateTime($rdv->getDate()->format('Y-m-d H:i:s'));
  1724.                 $dateFin $dateFin->add(new DateInterval("PT" $audioMotif->getDuration() . "M"));
  1725.                 $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  1726.                 $name $rdv->getIdProche() ? $rdv->getIdProche()->getName() : $client->getName();
  1727.                 $lastName $rdv->getIdProche() ? $rdv->getIdProche()->getLastname() : $client->getLastname();
  1728.                 $rdvItem = [
  1729.                     "id" => $rdv->getId(),
  1730.                     "title" => $lastName ' ' $name,
  1731.                     "start" => $rdv->getDate()->format('Y-m-d H:i:s'),
  1732.                     "end"   => $dateFin->format('Y-m-d H:i:s'),
  1733.                     "backgroundColor" => $audioMotif->getColor(),
  1734.                     "editable" => true,
  1735.                     "durationEditable" => false,
  1736.                     "resourceEditable" => true,
  1737.                     "cache" => false,
  1738.                     "motif_id" => $rdv->getIdMotif()->getId(),
  1739.                     "motif" => $motif->getTitre(),
  1740.                     "duree" => $audioMotif->getDuration(),
  1741.                     "color" => $audioMotif->getColor(),
  1742.                     "color_motif" => $audioMotif->getColor(),
  1743.                     "client_id" => $client->getId(),
  1744.                     "clientName" => $name,
  1745.                     "clientLastName" => $lastName,
  1746.                     "mail" => $client->getMail(),
  1747.                     "telephone" => $client->getPhone(),
  1748.                     "birthday" => $client->getBirthdate(),
  1749.                     "etat_id" => $rdv->getIdEtat()->getId(),
  1750.                     "dateDeb" => $rdv->getDate()->format('Y-m-d H:i:s'),
  1751.                     "dateFin" => $dateFin->format('Y-m-d H:i:s'),
  1752.                     "commentaire" => $rdv->getNote(),
  1753.                     "event_title" => "<b>" $lastName "</b> " $name,
  1754.                 ];
  1755.                 //  if ($rdv->getDate() >= new DateTime())
  1756.                 $rdvResult->add($rdvItem);
  1757.             }
  1758.         }
  1759.         if (count($rdvResult) > 0) {
  1760.             return new Response(json_encode(
  1761.                 $rdvResult->toArray(),
  1762.             ));
  1763.         } else {
  1764.             $rdvItem = [];
  1765.             //$rdvResult->add($rdvItem);
  1766.             return new Response(json_encode(
  1767.                 $rdvResult->toArray(),
  1768.             ));
  1769.         }
  1770.     }
  1771.     /**
  1772.      * @Route("/audio/{id}/rdvs/count", name="getCountAudioRdvs", methods={"GET","HEAD"})
  1773.      */
  1774.     public function getCountAudioRdvs(Request $requestAudio $audio)
  1775.     {
  1776.         if (!$request->query->get('token')) {
  1777.             return new Response(json_encode([
  1778.                 "message" => "Pas de token n'a été spécifié",
  1779.                 "status" => 401,
  1780.             ]), 401);
  1781.         }
  1782.         $entityManager $this->getDoctrine()->getManager();
  1783.         /** @var Token */
  1784.         $token $this->getDoctrine()
  1785.             ->getRepository(Token::class)
  1786.             ->findOneBy(['token' => $request->query->get('token')]);
  1787.         if (!$token) {
  1788.             return new Response(json_encode([
  1789.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1790.                 "status" => 404,
  1791.             ]), 404);
  1792.         }
  1793.         // get token age
  1794.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1795.         // if the token if older than 7 days
  1796.         if ($dateDiff->7) {
  1797.             $entityManager->remove($token);
  1798.             $entityManager->flush();
  1799.             return $this->json([
  1800.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1801.                 'path' => 'src/Controller/ClientController.php',
  1802.                 "status" => 401,
  1803.             ], 401);
  1804.         }
  1805.         if ($audio != $token->getIdAudio()) {
  1806.             return new Response(json_encode([
  1807.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  1808.                 "status" => 404,
  1809.             ]), 404);
  1810.         }
  1811.         /** @var Rdv[] */
  1812.         $rdvs $this->getDoctrine()
  1813.             ->getRepository(Rdv::class)
  1814.             ->findBy(['id_audio' => $audio->getId()]);
  1815.         return new Response(json_encode(([
  1816.             "content" => count($rdvs),
  1817.             "status" => 200,
  1818.         ])));
  1819.     }
  1820.     /**
  1821.      * @Route("/audio/{id}/rdvsDate/count", name="getCountAudioRdvsBetweenDate", methods={"GET","HEAD"})
  1822.      */
  1823.     public function getCountAudioRdvsBetweenDate(Request $requestAudio $audio)
  1824.     {
  1825.         if (!$request->query->get('token')) {
  1826.             return new Response(json_encode([
  1827.                 "message" => "Pas de token n'a été spécifié",
  1828.                 "status" => 401,
  1829.             ]), 401);
  1830.         }
  1831.         $entityManager $this->getDoctrine()->getManager();
  1832.         /** @var Token */
  1833.         $token $this->getDoctrine()
  1834.             ->getRepository(Token::class)
  1835.             ->findOneBy(['token' => $request->query->get('token')]);
  1836.         if (!$token) {
  1837.             return new Response(json_encode([
  1838.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1839.                 "status" => 404,
  1840.             ]), 404);
  1841.         }
  1842.         // get token age
  1843.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1844.         // if the token if older than 7 days
  1845.         if ($dateDiff->7) {
  1846.             $entityManager->remove($token);
  1847.             $entityManager->flush();
  1848.             return $this->json([
  1849.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1850.                 'path' => 'src/Controller/ClientController.php',
  1851.                 "status" => 401,
  1852.             ], 401);
  1853.         }
  1854.         if ($audio != $token->getIdAudio()) {
  1855.             return new Response(json_encode([
  1856.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  1857.                 "status" => 404,
  1858.             ]), 404);
  1859.         }
  1860.         /** @var Rdv[] */
  1861.         $allRdvs $this->getDoctrine()
  1862.             ->getRepository(Rdv::class)
  1863.             ->findOnlyRdvAudioBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1864.         /** @var Rdv[] */
  1865.         $rdvs $this->getDoctrine()
  1866.             ->getRepository(Rdv::class)
  1867.             ->findOnlyRdvAudioWithoutTestBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1868.         /** @var Rdv[] */
  1869.         $rdvsWithTest $this->getDoctrine()
  1870.             ->getRepository(Rdv::class)
  1871.             ->findOnlyRdvAudioWithTestBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1872.         /** @var Rdv[] */
  1873.         $allRdvsCanceled $this->getDoctrine()
  1874.             ->getRepository(Rdv::class)
  1875.             ->findCanceledRdvAudioBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1876.         /** @var Rdv[] */
  1877.         $allRdvsCanceledCentre $this->getDoctrine()
  1878.             ->getRepository(Rdv::class)
  1879.             ->findCanceledRdvCentreBetweenDate(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1880.         /** @var Rdv[] */
  1881.         $rdvsClosed $this->getDoctrine()
  1882.             ->getRepository(Rdv::class)
  1883.             ->findClosedRdvBetweenDate(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1884.         $myLead 0;
  1885.         $rdvsCanceled $this->getDoctrine()
  1886.             ->getRepository(Rdv::class)
  1887.             ->findCanceledRdvAudioBetweenDateWithoutTest($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1888.         foreach ($rdvsCanceled as $rdvc) {
  1889.             if (!is_null($rdvc->getIdClient())) {
  1890.                 $rdvClient $this->getDoctrine()
  1891.                     ->getRepository(Rdv::class)
  1892.                     ->findRDVLeadByClient(new DateTime($request->query->get('debut')), $request->query->get('centre'), $rdvc->getIdClient()->getID());
  1893.                 if (count($rdvClient) == 0) {
  1894.                     $myLead $myLead 1;
  1895.                 }
  1896.             }
  1897.         }
  1898.         $myLeadAdvanced 0;
  1899.         $rdvsCanceledA $this->getDoctrine()
  1900.             ->getRepository(Rdv::class)
  1901.             ->findCanceledRdvAudioBetweenDateWithTest($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1902.         foreach ($rdvsCanceledA as $rdvc) {
  1903.             if (!is_null($rdvc->getIdClient())) {
  1904.                 $rdvClient $this->getDoctrine()
  1905.                     ->getRepository(Rdv::class)
  1906.                     ->findRDVLeadByClient(new DateTime($request->query->get('debut')), $request->query->get('centre'), $rdvc->getIdClient()->getID());
  1907.                 if (count($rdvClient) == 0) {
  1908.                     $myLeadAdvanced $myLeadAdvanced 1;
  1909.                 }
  1910.             }
  1911.         }
  1912.         /**** MY RDV Centre****/
  1913.         $myrdvCentre 0;
  1914.         $rdvs $this->getDoctrine()
  1915.             ->getRepository(Rdv::class)
  1916.             ->findRDVCentreBetweenDateWithoutTest(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1917.         $myrdvCentre count($rdvs);
  1918.         /**** MY RDV ADVANCED ****/
  1919.         $myRdvAdvancedCentre 0;
  1920.         $rdvsA $this->getDoctrine()
  1921.             ->getRepository(Rdv::class)
  1922.             ->findRDVCentreBetweenDateWithTestId(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1923.         $myRdvAdvancedCentre count($rdvsA);
  1924.         /**** FIRST RDV BY MOTIF PREMIER RDV ****/
  1925.         $myFirstRdv 0;
  1926.         $rdvsFirst $this->getDoctrine()
  1927.             ->getRepository(Rdv::class)
  1928.             ->findFirstRdv(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1929.         $myFirstRdv count($rdvsFirst);
  1930.         /****  RDV BY RECHERCHE RESULT VIA MYAUDIO ****/
  1931.         $myAudioRdv 0;
  1932.         $audioRdv $this->getDoctrine()
  1933.             ->getRepository(Rdv::class)
  1934.             ->findRdvMyAudio(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1935.         $myAudioRdv count($audioRdv);
  1936.         /****  RDV BY GENDER ****/
  1937.         $myRdvByGender 0;
  1938.         $audioRdvGender $this->getDoctrine()
  1939.             ->getRepository(Rdv::class)
  1940.             ->countMaleAndFemalePatient(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1941.         $myRdvByGender $audioRdvGender;
  1942.         /****  RDV BY AGE ****/
  1943.         $myRdvByAge 0;
  1944.         $audioRdvAge $this->getDoctrine()
  1945.             ->getRepository(Rdv::class)
  1946.             ->countClientsByAgeGroupsPatient(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1947.         $myRdvByAge $audioRdvAge;
  1948.         //  dd($myRdvByAge);
  1949.         /**** MY LEAD ****/
  1950.         $myLeadCentre 0;
  1951.         $rdvsCanceled $this->getDoctrine()
  1952.             ->getRepository(Rdv::class)
  1953.             ->findCanceledRdvCentreBetweenDateWithoutTest(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1954.         foreach ($rdvsCanceled as $rdvc) {
  1955.             if (!is_null($rdvc->getIdClient())) {
  1956.                 $rdvClient $this->getDoctrine()
  1957.                     ->getRepository(Rdv::class)
  1958.                     ->findRDVLeadByClient(new DateTime($request->query->get('debut')), $request->query->get('centre'), $rdvc->getIdClient()->getID());
  1959.                 if (count($rdvClient) == 0) {
  1960.                     $myLeadCentre $myLeadCentre 1;
  1961.                 }
  1962.             }
  1963.         }
  1964.         /**** MY LEAD ADVANCED****/
  1965.         $myLeadAdvancedCentre 0;
  1966.         $rdvsCanceledA $this->getDoctrine()
  1967.             ->getRepository(Rdv::class)
  1968.             ->findCanceledRdvCentreBetweenDateWithTest(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1969.         foreach ($rdvsCanceledA as $rdvc) {
  1970.             if (!is_null($rdvc->getIdClient())) {
  1971.                 $rdvClient $this->getDoctrine()
  1972.                     ->getRepository(Rdv::class)
  1973.                     ->findRDVLeadByClient(new DateTime($request->query->get('debut')), $request->query->get('centre'), $rdvc->getIdClient()->getID());
  1974.                 if (count($rdvClient) == 0) {
  1975.                     $myLeadAdvancedCentre $myLeadAdvancedCentre 1;
  1976.                 }
  1977.             }
  1978.         }
  1979.         return $this->json([
  1980.             "rdvs" => count($rdvs),
  1981.             "rdvsFromTest" => count($rdvsWithTest),
  1982.             "allRdvs" => count($allRdvs),
  1983.             "rdvsCanceled" => count($allRdvsCanceled),
  1984.             "rdvsClosed" => $rdvsClosed,
  1985.             "myRdvByGender" => $myRdvByGender,
  1986.             "myLead" => $myLead,
  1987.             "myRdvByAge" => $myRdvByAge,
  1988.             "myAudioRdv" => $myAudioRdv,
  1989.             "myLeadAdvanced" => $myLeadAdvanced,
  1990.             "myRDVCentre" => $myrdvCentre,
  1991.             "myRDVAdancedCentre" => $myRdvAdvancedCentre,
  1992.             "myLeadCentre" => $myLeadCentre,
  1993.             "myLeadAdvancedCentre" => $myLeadAdvancedCentre,
  1994.             "rdvsCanceledCentre" => count($allRdvsCanceledCentre),
  1995.             "myFirstRdv" => $myFirstRdv,
  1996.             "status" => 200,
  1997.         ]);
  1998.     }
  1999.     /**
  2000.      * @Route("/rdvs/old/clientTemp/{id}", name="getOldRdvsByClientTempId", methods={"GET","HEAD"})
  2001.      */
  2002.     public function getOldRdvsByClientTempId(Request $requestClientTemp $clientTempPublicFunction $publicFunction)
  2003.     {
  2004.         if (!$request->query->get('token')) {
  2005.             return new Response(json_encode([
  2006.                 "message" => "Pas de token n'a été spécifié",
  2007.                 "status" => 401,
  2008.             ]), 401);
  2009.         }
  2010.         $entityManager $this->getDoctrine()->getManager();
  2011.         /** @var Token */
  2012.         $token $this->getDoctrine()
  2013.             ->getRepository(Token::class)
  2014.             ->findOneBy(['token' => $request->query->get('token')]);
  2015.         if (!$token) {
  2016.             return new Response(json_encode([
  2017.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2018.                 "status" => 404,
  2019.             ]), 404);
  2020.         }
  2021.         // get token age
  2022.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2023.         // if the token if older than 7 days
  2024.         if ($dateDiff->7) {
  2025.             $entityManager->remove($token);
  2026.             $entityManager->flush();
  2027.             return $this->json([
  2028.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2029.                 'path' => 'src/Controller/ClientController.php',
  2030.                 "status" => 401,
  2031.             ], 401);
  2032.         }
  2033.         if ($clientTemp->getIdAudio() != $token->getIdAudio()) {
  2034.             return new Response(json_encode([
  2035.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  2036.                 "status" => 404,
  2037.             ]), 404);
  2038.         }
  2039.         if ($request->query->get('audio')) {
  2040.             /** @var ActivityRepository */
  2041.             $activityRepo $this->getDoctrine()->getRepository(Rdv::class);
  2042.             if ($request->query->get('limit')) {
  2043.                 /** @var Rdv[] */
  2044.                 $rdvs $activityRepo
  2045.                     ->findLastsOldRdvsWithLimitTemp($request->query->get('limit'), $clientTemp->getId(), $request->query->get('audio'), new DateTime());
  2046.                 $rdvResult = new ArrayCollection();
  2047.             } else {
  2048.                 /** @var Rdv[] */
  2049.                 $rdvs $activityRepo
  2050.                     ->findOldRdvsTemp($clientTemp->getId(), $request->query->get('audio'), new DateTime());
  2051.                 $rdvResult = new ArrayCollection();
  2052.             }
  2053.             foreach ($rdvs as $rdv) {
  2054.                 if ($rdv->getIdEtat()->getId() != 1) {
  2055.                     continue;
  2056.                 }
  2057.                 /** @var AudioMotif */
  2058.                 $audioMotif $this->getDoctrine()
  2059.                     ->getRepository(AudioMotif::class)
  2060.                     ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  2061.                 if (!$audioMotif) {
  2062.                     continue;
  2063.                 }
  2064.                 $duration '';
  2065.                 if (is_null($rdv->getDuration())) {
  2066.                     $duration $audioMotif->getDuration();
  2067.                 } else {
  2068.                     $duration $rdv->getDuration();
  2069.                 }
  2070.                 $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  2071.                 /** @var Rdv[] */
  2072.                 $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  2073.                     ->findAllReviewsCentre($rdvCentre->getId());
  2074.                 $rdvItem = [
  2075.                     "id" => $rdv->getId(),
  2076.                     "motif_id" => $rdv->getIdMotif()->getId(),
  2077.                     "duration" => $duration,
  2078.                     "color" => $audioMotif->getColor(),
  2079.                     "audio_id" => $rdv->getIdAudio()->getId(),
  2080.                     "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  2081.                     "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  2082.                     "client_id_temp" => $rdv->getIdClientTemp()->getId(),
  2083.                     "client_name" => $rdv->getIdClientTemp()->getName() . " " $rdv->getIdClientTemp()->getLastname(),
  2084.                     "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  2085.                     "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  2086.                     "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  2087.                     "testclient" => $rdv->getTestClient() ? [
  2088.                         "result" => $rdv->getTestClient()->getResultTonal(),
  2089.                         "date" => $rdv->getTestClient()->getDate(),
  2090.                         "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  2091.                     ] : null,
  2092.                     "name" => $rdvCentre->getName(),
  2093.                     "phone" => $rdvCentre->getPhone(),
  2094.                     "imgUrl" => $rdvCentre->getImgUrl(),
  2095.                     "address" => $rdvCentre->getAddress(),
  2096.                     "postale" => $rdvCentre->getPostale(),
  2097.                     "city" => $rdvCentre->getCity(),
  2098.                     "etat_id" => $rdvCentre->getId(),
  2099.                     "averageRating" => $publicFunction->calculateRating($centreRdvs),
  2100.                     "nbrReview" => count($centreRdvs),
  2101.                     "acceptedCurrency" => "CB Chèque",
  2102.                     "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  2103.                     "note" => $rdv->getNote(),
  2104.                     "comment" => $rdv->getComment(),
  2105.                     "review" => $rdv->getReview(),
  2106.                 ];
  2107.                 $rdvResult->add($rdvItem);
  2108.             }
  2109.         }
  2110.         if (count($rdvResult) > 0) {
  2111.             return new Response(json_encode(([
  2112.                 "rdv" => $rdvResult->toArray(),
  2113.                 "status" => 200,
  2114.             ])));
  2115.         } else {
  2116.             return new Response(json_encode(([
  2117.                 "message" => "Aucun rendez-vous n'a été trouvé!",
  2118.                 'path' => 'src/Controller/RdvController.php',
  2119.                 "status" => 404,
  2120.             ])));
  2121.         }
  2122.     }
  2123.     /**
  2124.      * @Route("/rdvs/old/clientTemp/{id}/centre", name="getOldRdvsByClientTempIdByCentre", methods={"GET","HEAD"})
  2125.      */
  2126.     public function getOldRdvsByClientTempIdByCentre(Request $requestClientTemp $clientTempPublicFunction $publicFunction)
  2127.     {
  2128.         if (!$request->query->get('token')) {
  2129.             return new Response(json_encode([
  2130.                 "message" => "Pas de token n'a été spécifié",
  2131.                 "status" => 401,
  2132.             ]), 401);
  2133.         }
  2134.         $entityManager $this->getDoctrine()->getManager();
  2135.         /** @var Token */
  2136.         $token $this->getDoctrine()
  2137.             ->getRepository(Token::class)
  2138.             ->findOneBy(['token' => $request->query->get('token')]);
  2139.         if (!$token) {
  2140.             return new Response(json_encode([
  2141.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2142.                 "status" => 404,
  2143.             ]), 404);
  2144.         }
  2145.         // get token age
  2146.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2147.         // if the token if older than 7 days
  2148.         if ($dateDiff->7) {
  2149.             $entityManager->remove($token);
  2150.             $entityManager->flush();
  2151.             return $this->json([
  2152.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2153.                 'path' => 'src/Controller/ClientController.php',
  2154.                 "status" => 401,
  2155.             ], 401);
  2156.         }
  2157.         $audioCentre $this->getDoctrine()
  2158.             ->getRepository(AudioCentre::class)
  2159.             ->findOneBy(['id_audio' => $token->getIdAudio()]);
  2160.         // we add the multi-centre so we wil desable the autorisation 
  2161.         /*
  2162.         if ($clientTemp->getIdCentre() != $audioCentre->getIdCentre()) {
  2163.             return new Response(json_encode([
  2164.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  2165.                 "status" => 404,
  2166.             ]), 404);
  2167.         }
  2168. */
  2169.         /** @var ActivityRepository */
  2170.         $activityRepo $this->getDoctrine()->getRepository(Rdv::class);
  2171.         if ($request->query->get('limit')) {
  2172.             /** @var Rdv[] */
  2173.             $rdvs $activityRepo
  2174.                 ->findLastsOldRdvsWithLimitTempByCentre($request->query->get('limit'), $clientTemp->getId(), $audioCentre->getIdCentre()->getId(), new DateTime());
  2175.             $rdvResult = new ArrayCollection();
  2176.         } else {
  2177.             /** @var Rdv[] */
  2178.             $rdvs $activityRepo
  2179.                 ->findOldRdvsTempByCentre($clientTemp->getId(), $audioCentre->getIdCentre()->getId(), new DateTime());
  2180.             $rdvResult = new ArrayCollection();
  2181.         }
  2182.         foreach ($rdvs as $rdv) {
  2183.             /*if ($rdv->getIdEtat()->getId() != 1) {
  2184.                 continue;
  2185.             }*/
  2186.             /** @var AudioMotif */
  2187.             $audioMotif $this->getDoctrine()
  2188.                 ->getRepository(AudioMotif::class)
  2189.                 ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  2190.             if (!$audioMotif) {
  2191.                 continue;
  2192.             }
  2193.             $duration '';
  2194.             if (is_null($rdv->getDuration())) {
  2195.                 $duration $audioMotif->getDuration();
  2196.             } else {
  2197.                 $duration $rdv->getDuration();
  2198.             }
  2199.             $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  2200.             /** @var Rdv[] */
  2201.             $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  2202.                 ->findAllReviewsCentre($rdvCentre->getId());
  2203.             $rdvItem = [
  2204.                 "id" => $rdv->getId(),
  2205.                 "motif_id" => $rdv->getIdMotif()->getId(),
  2206.                 "duration" => $duration,
  2207.                 "color" => $audioMotif->getColor(),
  2208.                 "audio_id" => $rdv->getIdAudio()->getId(),
  2209.                 "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  2210.                 "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  2211.                 "client_id_temp" => $rdv->getIdClientTemp()->getId(),
  2212.                 "client_name" => $rdv->getIdClientTemp()->getName() . " " $rdv->getIdClientTemp()->getLastname(),
  2213.                 "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  2214.                 "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  2215.                 "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  2216.                 "testclient" => $rdv->getTestClient() ? [
  2217.                     "result" => $rdv->getTestClient()->getResultTonal(),
  2218.                     "date" => $rdv->getTestClient()->getDate(),
  2219.                     "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  2220.                 ] : null,
  2221.                 "name" => $rdvCentre->getName(),
  2222.                 "phone" => $rdvCentre->getPhone(),
  2223.                 "imgUrl" => $rdvCentre->getImgUrl(),
  2224.                 "address" => $rdvCentre->getAddress(),
  2225.                 "postale" => $rdvCentre->getPostale(),
  2226.                 "city" => $rdvCentre->getCity(),
  2227.                 "etat_id" => $rdvCentre->getId(),
  2228.                 "averageRating" => $publicFunction->calculateRating($centreRdvs),
  2229.                 "nbrReview" => count($centreRdvs),
  2230.                 "acceptedCurrency" => "CB Chèque",
  2231.                 "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  2232.                 "note" => $rdv->getNote(),
  2233.                 "comment" => $rdv->getComment(),
  2234.                 "review" => $rdv->getReview(),
  2235.                 "status" => $rdv->getIdEtat()->getLibelle()
  2236.             ];
  2237.             $rdvResult->add($rdvItem);
  2238.         }
  2239.         if (count($rdvResult) > 0) {
  2240.             return new Response(json_encode(([
  2241.                 "rdv" => $rdvResult->toArray(),
  2242.                 "status" => 200,
  2243.             ])));
  2244.         } else {
  2245.             return new Response(json_encode(([
  2246.                 "message" => "Aucun rendez-vous n'a été trouvé!",
  2247.                 'path' => 'src/Controller/RdvController.php',
  2248.                 "status" => 404,
  2249.             ])));
  2250.         }
  2251.     }
  2252.     /**
  2253.      * @Route("/rdvs/clientTemp/{id}", name="getRdvsByClientTempID", methods={"GET","HEAD"})
  2254.      */
  2255.     public function getRdvsByClientTempID(Request $requestClientTemp $clientTempPublicFunction $publicFunction)
  2256.     {
  2257.         if (!$request->query->get('token')) {
  2258.             return new Response(json_encode([
  2259.                 "message" => "Pas de token n'a été spécifié",
  2260.                 "status" => 401,
  2261.             ]), 401);
  2262.         }
  2263.         $entityManager $this->getDoctrine()->getManager();
  2264.         /** @var Token */
  2265.         $token $this->getDoctrine()
  2266.             ->getRepository(Token::class)
  2267.             ->findOneBy(['token' => $request->query->get('token')]);
  2268.         if (!$token) {
  2269.             return new Response(json_encode([
  2270.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2271.                 "status" => 404,
  2272.             ]), 404);
  2273.         }
  2274.         // get token age
  2275.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2276.         // if the token if older than 7 days
  2277.         if ($dateDiff->7) {
  2278.             $entityManager->remove($token);
  2279.             $entityManager->flush();
  2280.             return $this->json([
  2281.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2282.                 'path' => 'src/Controller/ClientController.php',
  2283.                 "status" => 401,
  2284.             ], 401);
  2285.         }
  2286.         if ($clientTemp->getIdAudio() != $token->getIdAudio()) {
  2287.             return new Response(json_encode([
  2288.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  2289.                 "status" => 404,
  2290.             ]), 404);
  2291.         }
  2292.         /** @var Rdv[] */
  2293.         $rdvs $this->getDoctrine()
  2294.             ->getRepository(Rdv::class)
  2295.             ->findBy(['id_client_temp' => $clientTemp->getId(), 'id_audio' => $token->getIdAudio()]);
  2296.         $rdvResult = new ArrayCollection();
  2297.         if ($request->query->get('old')) {
  2298.             $oldRdvResult = new ArrayCollection();
  2299.         }
  2300.         foreach ($rdvs as $rdv) {
  2301.             if ($rdv->getIdEtat()->getId() != null) {
  2302.                 if ($rdv->getIdEtat()->getId() == 1) {
  2303.                     /** @var AudioMotif */
  2304.                     $audioMotif $this->getDoctrine()
  2305.                         ->getRepository(AudioMotif::class)
  2306.                         ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $token->getIdAudio()]);
  2307.                     /** @var Rdv[] */
  2308.                     $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  2309.                         ->findAllReviewsCentre($rdv->getIdCentre()->getId());
  2310.                     $duration '';
  2311.                     if (is_null($rdv->getDuration())) {
  2312.                         $duration $audioMotif->getDuration();
  2313.                     } else {
  2314.                         $duration $rdv->getDuration();
  2315.                     }
  2316.                     $rdvItem = [
  2317.                         "id" => $rdv->getId(),
  2318.                         "motif_id" => $rdv->getIdMotif()->getId(),
  2319.                         "duration" => $duration,
  2320.                         "color" => $audioMotif->getColor(),
  2321.                         "audio_id" => $rdv->getIdAudio()->getId(),
  2322.                         "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  2323.                         "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  2324.                         "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  2325.                         "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  2326.                         "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  2327.                         "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  2328.                         "client_name" => $rdv->getIdClientTemp()->getName() . " " $rdv->getIdClientTemp()->getLastname(),
  2329.                         "averageRating" => $publicFunction->calculateRating($centreRdvs),
  2330.                         "nbrReview" => count($centreRdvs),
  2331.                         "acceptedCurrency" => "CB Chèque",
  2332.                         "name" => $rdv->getIdCentre()->getName(),
  2333.                         "imgUrl" => $rdv->getIdCentre()->getImgUrl(),
  2334.                         "address" => $rdv->getIdCentre()->getAddress(),
  2335.                         "phone" => $rdv->getIdCentre()->getPhone(),
  2336.                         "etat_id" => $rdv->getIdEtat()->getId(),
  2337.                         "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  2338.                         "comment" => $rdv->getComment(),
  2339.                         "note" => $rdv->getNote(),
  2340.                         "review" => $rdv->getReview(),
  2341.                     ];
  2342.                     if ($rdv->getDate() >= new DateTime()) {
  2343.                         $rdvResult->add($rdvItem);
  2344.                     } else if ($request->query->get('old')) {
  2345.                         $oldRdvResult->add($rdvItem);
  2346.                     }
  2347.                 }
  2348.             }
  2349.         }
  2350.         if ($request->query->get('old')) {
  2351.             if (count($rdvResult) > || count($oldRdvResult) > 0) {
  2352.                 return new Response(json_encode(([
  2353.                     "rdv" => $rdvResult->toArray(),
  2354.                     "oldRdv" => $oldRdvResult->toArray(),
  2355.                     "status" => 200,
  2356.                 ])));
  2357.             } else {
  2358.                 return new Response(json_encode(([
  2359.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  2360.                     'path' => 'src/Controller/RdvController.php',
  2361.                     "status" => 404,
  2362.                 ])));
  2363.             }
  2364.         } else {
  2365.             if (count($rdvResult) > 0) {
  2366.                 return new Response(json_encode(([
  2367.                     "content" => $rdvResult->toArray(),
  2368.                     "status" => 200,
  2369.                 ])));
  2370.             } else {
  2371.                 return new Response(json_encode(([
  2372.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  2373.                     'path' => 'src/Controller/RdvController.php',
  2374.                     "status" => 404,
  2375.                 ])));
  2376.             }
  2377.         }
  2378.     }
  2379.     /**
  2380.      * @Route("/rdvs/clientTemp/{id}/centre", name="getRdvsByClientTempIDByCentre", methods={"GET","HEAD"})
  2381.      */
  2382.     public function getRdvsByClientTempIDByCentre(Request $requestClientTemp $clientTempPublicFunction $publicFunction)
  2383.     {
  2384.         if (!$request->query->get('token')) {
  2385.             return new Response(json_encode([
  2386.                 "message" => "Pas de token n'a été spécifié",
  2387.                 "status" => 401,
  2388.             ]), 401);
  2389.         }
  2390.         $entityManager $this->getDoctrine()->getManager();
  2391.         /** @var Token */
  2392.         $token $this->getDoctrine()
  2393.             ->getRepository(Token::class)
  2394.             ->findOneBy(['token' => $request->query->get('token')]);
  2395.         if (!$token) {
  2396.             return new Response(json_encode([
  2397.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2398.                 "status" => 404,
  2399.             ]), 404);
  2400.         }
  2401.         // get token age
  2402.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2403.         // if the token if older than 7 days
  2404.         if ($dateDiff->7) {
  2405.             $entityManager->remove($token);
  2406.             $entityManager->flush();
  2407.             return $this->json([
  2408.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2409.                 'path' => 'src/Controller/ClientController.php',
  2410.                 "status" => 401,
  2411.             ], 401);
  2412.         }
  2413.         $audioCentre $this->getDoctrine()
  2414.             ->getRepository(AudioCentre::class)
  2415.             ->findOneBy(['id_audio' => $token->getIdAudio()]);
  2416.         // we add the multi-centre so we wil desable the autorisation 
  2417.         /*    
  2418.         if ($clientTemp->getIdCentre() != $audioCentre->getIdCentre()) {
  2419.             return new Response(json_encode([
  2420.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  2421.                 "status" => 404,
  2422.             ]), 404);
  2423.         }*/
  2424.         /** @var Rdv[] */
  2425.         $rdvs $this->getDoctrine()
  2426.             ->getRepository(Rdv::class)
  2427.             ->findBy(['id_client_temp' => $clientTemp->getId(), 'id_centre' => $audioCentre->getIdCentre()]);
  2428.         $rdvResult = new ArrayCollection();
  2429.         if ($request->query->get('old')) {
  2430.             $oldRdvResult = new ArrayCollection();
  2431.         }
  2432.         foreach ($rdvs as $rdv) {
  2433.             if ($rdv->getIdEtat()->getId() != null) {
  2434.                 if ($rdv->getIdEtat()->getId() != 6) {
  2435.                     // if ($rdv->getIdEtat()->getId() == 1) {
  2436.                     /** @var AudioMotif */
  2437.                     $audioMotif $this->getDoctrine()
  2438.                         ->getRepository(AudioMotif::class)
  2439.                         ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  2440.                     /** @var Rdv[] */
  2441.                     $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  2442.                         ->findAllReviewsCentre($rdv->getIdCentre()->getId());
  2443.                     $duration '';
  2444.                     if (is_null($rdv->getDuration())) {
  2445.                         $duration $audioMotif->getDuration();
  2446.                     } else {
  2447.                         $duration $rdv->getDuration();
  2448.                     }
  2449.                     $rdvItem = [
  2450.                         "id" => $rdv->getId(),
  2451.                         "motif_id" => $rdv->getIdMotif()->getId(),
  2452.                         "duration" => $duration,
  2453.                         "color" => $audioMotif->getColor(),
  2454.                         "audio_id" => $rdv->getIdAudio()->getId(),
  2455.                         "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  2456.                         "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  2457.                         "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  2458.                         "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  2459.                         "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  2460.                         "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  2461.                         "client_name" => $rdv->getIdClientTemp()->getName() . " " $rdv->getIdClientTemp()->getLastname(),
  2462.                         "averageRating" => $publicFunction->calculateRating($centreRdvs),
  2463.                         "nbrReview" => count($centreRdvs),
  2464.                         "acceptedCurrency" => "CB Chèque",
  2465.                         "name" => $rdv->getIdCentre()->getName(),
  2466.                         "imgUrl" => $rdv->getIdCentre()->getImgUrl(),
  2467.                         "address" => $rdv->getIdCentre()->getAddress(),
  2468.                         "phone" => $rdv->getIdCentre()->getPhone(),
  2469.                         "etat_id" => $rdv->getIdEtat()->getId(),
  2470.                         "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  2471.                         "comment" => $rdv->getComment(),
  2472.                         "note" => $rdv->getNote(),
  2473.                         "review" => $rdv->getReview(),
  2474.                         "status" => $rdv->getIdEtat()->getLibelle()
  2475.                     ];
  2476.                     if ($rdv->getDate() >= new DateTime()) {
  2477.                         $rdvResult->add($rdvItem);
  2478.                     } else if ($request->query->get('old')) {
  2479.                         $oldRdvResult->add($rdvItem);
  2480.                     }
  2481.                 }
  2482.             }
  2483.         }
  2484.         if ($request->query->get('old')) {
  2485.             if (count($rdvResult) > || count($oldRdvResult) > 0) {
  2486.                 return new Response(json_encode(([
  2487.                     "rdv" => $rdvResult->toArray(),
  2488.                     "oldRdv" => $oldRdvResult->toArray(),
  2489.                     "status" => 200,
  2490.                 ])));
  2491.             } else {
  2492.                 return new Response(json_encode(([
  2493.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  2494.                     'path' => 'src/Controller/RdvController.php',
  2495.                     "status" => 404,
  2496.                 ])));
  2497.             }
  2498.         } else {
  2499.             if (count($rdvResult) > 0) {
  2500.                 return new Response(json_encode(([
  2501.                     "content" => $rdvResult->toArray(),
  2502.                     "status" => 200,
  2503.                 ])));
  2504.             } else {
  2505.                 return new Response(json_encode(([
  2506.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  2507.                     'path' => 'src/Controller/RdvController.php',
  2508.                     "status" => 404,
  2509.                 ])));
  2510.             }
  2511.         }
  2512.     }
  2513.     /**
  2514.      * @Route("/rdv", name="postRdv", methods={"POST"})
  2515.      */
  2516.     public function postRdv(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendarRdvSmsService $rdvSmsAppointmentCallService $Callservice): Response
  2517.     {
  2518.         $data json_decode($request->getContent(), true);
  2519.         if (!isset($data["token"])) {
  2520.             return new Response(json_encode([
  2521.                 "message" => "Pas de token n'a été spécifié",
  2522.                 "status" => 401,
  2523.             ]), 401);
  2524.         }
  2525.         $entityManager $this->getDoctrine()->getManager();
  2526.         /** @var Token */
  2527.         $token $this->getDoctrine()
  2528.             ->getRepository(Token::class)
  2529.             ->findOneBy(['token' => $data["token"]]);
  2530.         if (!$token) {
  2531.             return new Response(json_encode([
  2532.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2533.                 "status" => 404,
  2534.             ]), 404);
  2535.         }
  2536.         // get token age
  2537.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2538.         // if the token if older than 7 days
  2539.         if ($dateDiff->7) {
  2540.             $entityManager->remove($token);
  2541.             $entityManager->flush();
  2542.             return $this->json([
  2543.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2544.                 'path' => 'src/Controller/ClientController.php',
  2545.                 "status" => 401,
  2546.             ], 401);
  2547.         }
  2548.         // makes the rdv
  2549.         $rdv = new Rdv();
  2550.         if ($token->getIdAudio()) {
  2551.             //if the token if for an audio
  2552.             $audio $token->getIdAudio();
  2553.             if ((isset($data["client_id"]))) {
  2554.                 $client $this->getDoctrine()
  2555.                     ->getRepository(Client::class)
  2556.                     ->findOneBy(['id' => $data["client_id"]]);
  2557.             } else {
  2558.                 $client $this->getDoctrine()
  2559.                     ->getRepository(ClientTemp::class)
  2560.                     ->findOneBy(['id' => $data["client_id_temp"]]);
  2561.             }
  2562.             if ($client == null) {
  2563.                 return new Response(json_encode(([
  2564.                     'message' => 'Error, no client found at this id',
  2565.                     'path' => 'src/Controller/RdvController.php',
  2566.                     "status" => 400,
  2567.                 ])), 400);
  2568.             }
  2569.         } elseif ($token->getIdClient()) {
  2570.             //if the token if for a client
  2571.             $client $token->getIdClient();
  2572.             /** @var ActivityRepository */
  2573.             $activityRepo $this->getDoctrine();
  2574.             /** @var TestClient */
  2575.             $testClient $activityRepo
  2576.                 ->getRepository(TestClient::class)
  2577.                 ->getLatestTestClient($client);
  2578.             // add the test to the rdv if the client had one
  2579.             if ($testClient)
  2580.             // add the test to the rdv if the test isn't already on another rdv
  2581.             {
  2582.                 if (!$testClient->getRdv()) {
  2583.                     $rdv->setTestClient($testClient);
  2584.                 }
  2585.             }
  2586.             /** @var Audio */
  2587.             $audio $this->getDoctrine()
  2588.                 ->getRepository(Audio::class)
  2589.                 ->findOneBy(['id' => $data["audio_id"]]);
  2590.             if (isset($data["proche_id"])) {
  2591.                 $proche $this->getDoctrine()
  2592.                     ->getRepository(Proches::class)
  2593.                     ->findOneBy(['id' => $data["proche_id"], "id_client" => $client]);
  2594.             }
  2595.             if (!$audio) {
  2596.                 return new Response(json_encode(([
  2597.                     'message' => "Erreur, pas d'audio n'a été trouvé à cette id.",
  2598.                     'path' => 'src/Controller/RdvController.php',
  2599.                 ])), 400);
  2600.             }
  2601.             /** @var ClientBlocked */
  2602.             $clientBlocked $this->getDoctrine()
  2603.                 ->getRepository(ClientBlocked::class)
  2604.                 ->findOneBy(["id_audio" => $audio"id_client" => $client]);
  2605.             if ($clientBlocked) {
  2606.                 return new Response(json_encode(([
  2607.                     'message' => 'Erreur, vous avez été bloqué par cette audioprothésiste.',
  2608.                     'path' => 'src/Controller/RdvController.php',
  2609.                 ])), 400);
  2610.             }
  2611.             // set the rdv test
  2612.         } else {
  2613.             return new Response(json_encode(([
  2614.                 'message' => "Erreur, ce token n'est pas celui d'un client ou audioprothèsiste.",
  2615.                 'path' => 'src/Controller/RdvController.php',
  2616.             ])), 400);
  2617.         }
  2618.         $rdv->setIdAudio($audio);
  2619.         if (isset($proche)) {
  2620.             $rdv->setIdProche($proche);
  2621.         }
  2622.         if (isset($data["client_id_temp"])) {
  2623.             $rdv->setIdClientTemp($client);
  2624.         } else {
  2625.             $rdv->setIdClient($client);
  2626.         }
  2627.         if (isset($data["isMyaudio"])) {
  2628.             $rdv->setIsMyaudio(true);
  2629.         }
  2630.         if (isset($data["isRdvLead"])) {
  2631.             $rdv->setIsRdvLp(true);
  2632.         }
  2633.         if (isset($data["isRdvRapide"])) {
  2634.             $rdv->setIsRdvRapide(true);
  2635.         }
  2636.         if (isset($data["duree"])) {
  2637.             $rdv->setDuration($data["duree"]);
  2638.         }
  2639.         if (isset($data["color"])) {
  2640.             $rdv->setColor($data["color"]);
  2641.         }
  2642.         if (isset($data["lead"])) {
  2643.             $lead $this->getDoctrine()
  2644.                 ->getRepository(LeadRdv::class)
  2645.                 ->find($data["lead"]);
  2646.             $lead->setRdv($rdv);
  2647.             $leadStatus $this->entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'rdv_valider']);
  2648.             if ($leadStatus) {
  2649.                 $lead->setLeadStatus($leadStatus);
  2650.             }
  2651.         }
  2652.         /** @var Centre */
  2653.         if (isset($data["centre_id"])) {
  2654.             $centre $this->getDoctrine()
  2655.                 ->getRepository(Centre::class)
  2656.                 ->findOneBy(['id' => $data["centre_id"]]);
  2657.             if ($centre == null) {
  2658.                 return new Response(json_encode(([
  2659.                     'message' => 'Error, no centre found at this id',
  2660.                     'path' => 'src/Controller/RdvController.php',
  2661.                     "status" => 400,
  2662.                 ])), 400);
  2663.             }
  2664.             /** @var AudioCentre */
  2665.             $liaison $this->getDoctrine()
  2666.                 ->getRepository(AudioCentre::class)
  2667.                 ->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
  2668.             if ($liaison == null) {
  2669.                 return new Response(json_encode(([
  2670.                     'message' => 'Error, audio isnt part of the centre',
  2671.                     'path' => 'src/Controller/RdvController.php',
  2672.                     "status" => 400,
  2673.                 ])), 400);
  2674.             }
  2675.             $rdv->setIdCentre($centre);
  2676.         } elseif (isset($data["lieu_id"]) && $audio->getIsIndie()) {
  2677.             // tries to set the lieu if it's an audio indie
  2678.             $lieu $this->getDoctrine()
  2679.                 ->getRepository(Lieu::class)
  2680.                 ->findOneBy(['id' => $data["lieu_id"], 'id_gerant' => $data["audio_id"]]);
  2681.             if ($lieu == null) {
  2682.                 return new Response(json_encode(([
  2683.                     'message' => 'Error, no lieu found at this id',
  2684.                     'path' => 'src/Controller/RdvController.php',
  2685.                     "status" => 400,
  2686.                 ])), 400);
  2687.             }
  2688.             $rdv->setIdLieu($lieu);
  2689.         } else {
  2690.             return new Response(json_encode(([
  2691.                 'message' => 'Error, no lieu/centre id',
  2692.                 'path' => 'src/Controller/RdvController.php',
  2693.                 "status" => 400,
  2694.             ])), 400);
  2695.         }
  2696.         /** @var Motif */
  2697.         $motif $this->getDoctrine()
  2698.             ->getRepository(Motif::class)
  2699.             ->find($data["motif_id"]);
  2700.         if ($motif == null) {
  2701.             return new Response(json_encode(([
  2702.                 'message' => 'Error, no motif found at this id',
  2703.                 'path' => 'src/Controller/RdvController.php',
  2704.                 "status" => 400,
  2705.             ])), 400);
  2706.         }
  2707.         /** @var AudioMotif */
  2708.         $audioMotif $this->getDoctrine()
  2709.             ->getRepository(AudioMotif::class)
  2710.             ->findOneBy(["id_audio" => $audio->getId(), "id_motif" => $data["motif_id"]]);
  2711.         if ($audioMotif == null) {
  2712.             return new Response(json_encode(([
  2713.                 'message' => 'Error, no motif of this id found at this audio',
  2714.                 'path' => 'src/Controller/RdvController.php',
  2715.                 "status" => 400,
  2716.             ])), 400);
  2717.         }
  2718.         // remove the taken schedule by rdv to make sure there is no overlap
  2719.         $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  2720.         if (isset($data["note"])) {
  2721.             $rdv->setNote($data["note"]);
  2722.         }
  2723.         // test if the audio is available
  2724.         if ($audio->getIsIndie()) {
  2725.             if (isset($data["centre_id"])) {
  2726.                 if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  2727.                     return new Response(json_encode(([
  2728.                         'message' => 'Error, no horaire found for this audio',
  2729.                         'path' => 'src/Controller/RdvController.php',
  2730.                         "status" => 400,
  2731.                     ])), 400);
  2732.                 }
  2733.                 if ($publicFunction->calculScheduleFitDate($audio\DateTime::createFromFormat("d/m/Y H:i"$data["date"]), $audioMotif->getDuration(), $centre) == false) {
  2734.                     return new Response(json_encode(([
  2735.                         'message' => 'Error, no timestamp found at this time. Line n°' __LINE__,
  2736.                         'path' => 'src/Controller/RdvController.php',
  2737.                         "status" => 400,
  2738.                     ])), 400);
  2739.                 }
  2740.                 $remplacant_id $publicFunction->checkIfRemplacant($liaison->getHoraire(), $date);
  2741.             } else {
  2742.                 if ($lieu->getHoraire() == null || $lieu->getHoraire() == []) {
  2743.                     return new Response(json_encode(([
  2744.                         'message' => 'Error, no horaire found for this audio',
  2745.                         'path' => 'src/Controller/RdvController.php',
  2746.                         "status" => 400,
  2747.                     ])), 400);
  2748.                 }
  2749.                 if ($publicFunction->calculScheduleFitDate($audio\DateTime::createFromFormat("d/m/Y H:i"$data["date"]), $audioMotif->getDuration(), null$lieu) == false) {
  2750.                     return new Response(json_encode(([
  2751.                         'message' => 'Error, no timestamp found at this time. Line n°' __LINE__,
  2752.                         'path' => 'src/Controller/RdvController.php',
  2753.                         "status" => 400,
  2754.                     ])), 400);
  2755.                 }
  2756.                 $remplacant_id $publicFunction->checkIfRemplacant($lieu->getHoraire(), $date);
  2757.             }
  2758.         } else {
  2759.             if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  2760.                 return new Response(json_encode(([
  2761.                     'message' => 'Error, no horaire found for this audio',
  2762.                     'path' => 'src/Controller/RdvController.php',
  2763.                     "status" => 400,
  2764.                 ])), 400);
  2765.             }
  2766.             /*  if (!$publicFunction->calculScheduleFitDate($audio, \DateTime::createFromFormat("d/m/Y H:i", $data["date"]), $audioMotif->getDuration(), $centre))
  2767.                 return new Response(json_encode(([
  2768.                     'message' => "Error, no timestamp found at this time. Motif size: {$audioMotif->getDuration()} Line n°" . __LINE__,
  2769.                     'path' => 'src/Controller/RdvController.php',
  2770.                     "status" => 400,
  2771.                 ])), 400);*/
  2772.             $remplacant_id $publicFunction->checkIfRemplacant($liaison->getHoraire(), \DateTime::createFromFormat("d/m/Y H:i"$data["date"]));
  2773.         }
  2774.         $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  2775.         $existingRdv $this->getDoctrine()
  2776.             ->getRepository(Rdv::class)
  2777.             ->findOneBy([
  2778.                 'date' => $date,
  2779.                 'id_audio' => $audio,
  2780.                 'id_centre' => $rdv->getIdCentre() ?? null,
  2781.                 'id_lieu' => $rdv->getIdLieu()   ?? null,
  2782.             ]);
  2783.         if ($existingRdv) {
  2784.             return new Response(json_encode([
  2785.                 'message' => 'Un rendez-vous est déjà pris pour cette date et ce créneau.',
  2786.                 'status' => 400,
  2787.             ]), 400);
  2788.         }
  2789.         $rdv->setDate($date);
  2790.         $rdv->setDateCreation(\DateTime::createFromFormat("d/m/Y H:i"date('d/m/Y H:i')));
  2791.         /** @var EtatRdv */
  2792.         $etat $this->getDoctrine()
  2793.             ->getRepository(EtatRdv::class)
  2794.             ->findOneBy(['id' => $data["etat_id"]]);
  2795.         if ($etat == null) {
  2796.             return new Response(json_encode(([
  2797.                 'message' => 'Error, no etat found at this id',
  2798.                 'path' => 'src/Controller/RdvController.php',
  2799.                 "status" => 400,
  2800.             ])), 400);
  2801.         }
  2802.         $rdv->setIdEtat($etat);
  2803.         $rdv->setIdMotif($motif);
  2804.         $rdv->setIsAbsence(0);
  2805.         $rdv->setCacher(0);
  2806.         if ($remplacant_id != -1) {
  2807.             $remplacant $this->getDoctrine()
  2808.                 ->getRepository(Remplacant::class)
  2809.                 ->find($remplacant_id);
  2810.             $rdv->setRemplacant($remplacant);
  2811.         }
  2812.         $entityManager $this->getDoctrine()->getManager();
  2813.         $entityManager->persist($rdv);
  2814.         $entityManager->flush();
  2815.         /// SMSEMAIL A décommenter pour autoriser l'envoi de sms / email à la création de rdv par l'audio / le client SMSEMAIL ///
  2816.         $date $rdv->getDate();
  2817.         $smsDate $date->format('d-m-Y H:i');
  2818.         $locale 'fr_FR';
  2819.         $formatter = new IntlDateFormatter(
  2820.             $locale,
  2821.             IntlDateFormatter::FULL,
  2822.             IntlDateFormatter::SHORT,
  2823.             null,
  2824.             IntlDateFormatter::GREGORIAN,
  2825.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  2826.         );
  2827.         $smsDateLongFormat $formatter->format($date);
  2828.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  2829.         $client->setIdCentre($rdv->getIdCentre());
  2830.         $client->setIdAudio($rdv->getIdAudio());
  2831.         $entityManager->persist($client);
  2832.         $entityManager->flush();
  2833.         // client notif mail Sms
  2834.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  2835.         $frenchDate ucfirst($frenchDate);
  2836.         $responses = [
  2837.             'rangeAge' => isset($data['rangeAge']) ? $data['rangeAge'] : null,
  2838.             'situations' => (isset($data['situations']) && !empty($data['situations'])) ? implode(", "$data['situations']) : null,
  2839.             'equipeAppareil' => isset($data['equipe']) ? $data['equipe'] : null,
  2840.             'durationEquipe' => isset($data['durationEquipe']) ? $data['durationEquipe'] : null,
  2841.             'bilanAuditif' => isset($data['bilanAuditif']) ? $data['bilanAuditif'] : null,
  2842.             'ordonance' => isset($data['ordonnance']) ? $data['ordonnance'] : null,
  2843.             'dateOrdonance' => isset($data['dateOrdonance']) ? $data['dateOrdonance'] : null,
  2844.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  2845.         ];
  2846.         $paramsSourceLead = [
  2847.             'trafficSource' => isset($data['traffic_source']) ? $data['traffic_source'] : null,
  2848.             'articleName' => isset($data['article_name']) ? $data['article_name'] : null,
  2849.             'lpVersion' => isset($data['lp_version']) ? $data['lp_version'] : null,
  2850.         ];
  2851.         $params = array(
  2852.             "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  2853.             "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  2854.             "date" => $smsDateLongFormat,
  2855.             "RdvDate" => $smsDateLongFormat,
  2856.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  2857.             "centerName" => $rdv->getIdCentre()->getName(),
  2858.             "prenom" => $client->getName(),
  2859.             "centerAddress" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  2860.             "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  2861.             'motif' => $rdv->getIdMotif()->getTitre(),
  2862.             "centerCity" => $rdv->getIdCentre()->getCity(),
  2863.             "audioName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  2864.             'titre' => "Votre rendez-vous est validé le " substr($smsDate010) . " à "  substr($smsDate1115),
  2865.             "position" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  2866.             "address" => $rdv->getIdCentre()->getAddress(),
  2867.             "postal" => $rdv->getIdCentre()->getPostale(),
  2868.             "city" => $rdv->getIdCentre()->getCity(),
  2869.             "clientEmail" => $client->getMail(),
  2870.             "clientPassword" => isset($data["passwordGenerated"]) ? $data["passwordGenerated"] : null,
  2871.             "clientAddress" => $client->getAddress(),
  2872.             "clientPostal" => $client->getPostal(),
  2873.             "clientCity" => $client->getCity(),
  2874.             "audioName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  2875.             "frenchDate" => $frenchDate,
  2876.             "heure" => substr($smsDate1115),
  2877.             "centerName" => $rdv->getIdCentre()->getName(),
  2878.             "audioMail" => $rdv->getIdAudio()->getMail(),
  2879.             "modifUrl" => "{$_ENV['BASE_client']}mes-rendez-vous",
  2880.         );
  2881.         $paramsPatient $params;
  2882.         $isNew false;
  2883.         if (isset($data["isLead"]) && isset($data["passwordGenerated"]) != null) {
  2884.             $subject "✅Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  2885.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject189);
  2886.             $isNew true;
  2887.         } else {
  2888.             $subject "Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  2889.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject181);
  2890.         }
  2891.         $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.";
  2892.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  2893.         // audio Notif mail SMS
  2894.         $birthday $rdv->getIdClient()->getBirthdate();
  2895.         $params = array(
  2896.             "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  2897.             "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  2898.             "date" => substr($smsDate010),
  2899.             "heure" => substr($smsDate1115),
  2900.             "mail" => $client->getMail(),
  2901.             "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  2902.             'telClient' => $client->getPhone(),
  2903.             'phone' => $client->getPhone(),
  2904.             'clientCivilite' => $client->getCivilite(),
  2905.             'clientNom' => $client->getLastname(),
  2906.             'clientPrenom' => $client->getName(),
  2907.             'clientPostal' => $client->getPostal(),
  2908.             'clientMail' => $client->getMail(),
  2909.             'clientPhone' => $client->getPhone(),
  2910.             'motif' => $rdv->getIdMotif()->getTitre(),
  2911.             'birthdate' => $client->getBirthdate() ? $client->getBirthdate()->format("d/m/Y") : null,
  2912.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  2913.             'centerName' => $rdv->getIdCentre()->getName(),
  2914.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  2915.             'centerCity' => $rdv->getIdCentre()->getCity(),
  2916.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  2917.             'idPatient' => $client->getId(),
  2918.             'proUrl' => "{$_ENV['BASE_logiciel']}",
  2919.             'frenchDate' => $frenchDate,
  2920.             'responses' => $responses,
  2921.         );
  2922.         $templateEmail 182;
  2923.         if (!empty($data['canMove'])) {
  2924.             $templateEmail 197;
  2925.         }
  2926.         $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  2927.         $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  2928.         if ($rdv->getIdAudio()->getConfirmRdvMail()) {
  2929.             $subject "✅Nouveau Rendez-vous My Audio le " $frenchDate " à " substr($smsDate1115);
  2930.             $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject$templateEmail);
  2931.         }
  2932.         if ($rdv->getIdAudio()->getConfirmRdvSms()) {
  2933.             $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.";
  2934.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  2935.         }
  2936.         // send notif to admin
  2937.         $paramsAdmin = array(
  2938.             "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  2939.             "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  2940.             "RdvDate" => substr($smsDate010),
  2941.             "heure" => substr($smsDate1115),
  2942.             "clientMail" => $client->getMail(),
  2943.             "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  2944.             'telClient' => $client->getPhone(),
  2945.             'clientNom' => $client->getLastname(),
  2946.             'clientPrenom' => $client->getName(),
  2947.             'clientCivilite' => $client->getCivilite(),
  2948.             'clientPostal' => $client->getPostal(),
  2949.             'clientPhone' => $client->getPhone(),
  2950.             'motif' => $rdv->getIdMotif()->getTitre(),
  2951.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  2952.             'centerName' => $rdv->getIdCentre()->getName(),
  2953.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  2954.             'centerCity' => $rdv->getIdCentre()->getCity(),
  2955.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  2956.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  2957.             'date' => substr($smsDate010),
  2958.             'urlApi' => "{$_ENV['BASE_API']}",
  2959.             'clientId' => $client->getId(),
  2960.             'centerId' => $rdv->getIdCentre()->getId(),
  2961.             'frenchDate' => $frenchDate,
  2962.             'responses' => $responses,
  2963.             'paramsSourceLead' => $paramsSourceLead
  2964.         );
  2965.         $subject "Nouveau RDV MA | RR - " $rdv->getIdCentre()->getName();
  2966.         $templateEmail 183;
  2967.         if (!empty($data['canMove'])) {
  2968.             $templateEmail 190;
  2969.         }
  2970.         if (!isset($data["isLead"])) {
  2971.             $publicFunction->sendEmail($paramsAdmin"lead.myaudio@gmail.com""my audio"$subject$templateEmail);
  2972.         }
  2973.         //$publicFunction->sendEmail($paramsAdmin,"testpation1254@myaudio.fr","my audio", 'Nouveau RDV à My Audio Pro', $templateEmail);
  2974.         $publicFunction->sendEmail($paramsAdmin"contact@myaudio.fr""my audio"$subject$templateEmail);
  2975.         $publicFunction->sendEmail($paramsAdmin"lead.myaudio@gmail.com""my audio"$subject$templateEmail);
  2976.         // google calendar post
  2977.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  2978.             ->findBy(array('audio' => $audio->getId()));
  2979.         $data['rdv'] = $rdv->getId();
  2980.         if (isset($data['clientRdvLp']) && !empty($data['clientRdvLp'])) {
  2981.             $rdvLead $this->entityManager->getRepository(LeadRdv::class)->find($data['clientRdvLp']);
  2982.             if ($rdvLead) {
  2983.                 $leadStatus $this->entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'rdv_valider']);
  2984.                 if ($leadStatus) {
  2985.                     $rdvLead->setLeadStatus($leadStatus);
  2986.                     $rdvLead->setRdv($rdv);
  2987.                     $this->entityManager->flush();
  2988.                 }
  2989.             }
  2990.         }
  2991.         foreach ($synchronisations as $synchronisation) {
  2992.             if (!$synchronisation->getIsDeleted()) {
  2993.                 $googleCalendar->checkAndRefreshAccessToken($synchronisation);
  2994.                 $googleCalendar->createEvent($synchronisation$data);
  2995.             }
  2996.         }
  2997.         if (isset($data["isMyaudio"]) || isset($data["isRdvLead"]) || isset($data["isRdvRapide"])) {
  2998.             try {
  2999.                 $Callservice->handleCallCenterAfterRdv(
  3000.                     $rdv
  3001.                 );
  3002.                 $rdv->setIsNotificationRdvCallSent(1);
  3003.                 $this->entityManager->flush();
  3004.             } catch (\Exception $e) {
  3005.                 $this->logger->error("Erreur lors de l'appel de notification pour le RDV #{$rdv->getId()}: " $e->getMessage());
  3006.             }
  3007.         }
  3008.         $token $this->entityManager
  3009.              ->getRepository(Token::class)
  3010.              ->findOneBy(['token' => $data['token']]);
  3011.         $tokenAudioId $token->getIdAudio()->getId();
  3012.         $requestAudioId $data['audio_id'] ?? null;
  3013.         if ($requestAudioId && $requestAudioId == $tokenAudioId) {
  3014.         // Only publish for this audio
  3015.         $this->mercure->publishRdvUpdate($rdv'created');
  3016.         }
  3017.          // Find the audio/user who owns the referral code
  3018.     $referrer $client// the user who shared the code
  3019.     // Make sure key exists
  3020.     $codeParrain $data['codeParrain'] ?? null;  // null if not provided
  3021.     if ($codeParrain) {
  3022.       // Find the new user/referee who is using the code 
  3023.       $referee $entityManager->getRepository(Client::class)->findOneBy([
  3024.           'referralCode' => $codeParrain
  3025.       ]);
  3026.     if ($referee) {
  3027.         $referral = new Referral();
  3028.         $referral->setReferrerType('patient'); 
  3029.         $referral->setReferrerId($referrer->getId()); 
  3030.         $referral->setRefereeType('patient'); 
  3031.         $referral->setRefereeId($referee->getId()); 
  3032.         $referral->setCodeUsed($codeParrain); 
  3033.         $referral->setStatus('pending');
  3034.         $referral->setRewardAmount(100); 
  3035.         $referral->setCreatedAt(new \DateTime());
  3036.         $entityManager->persist($referral);
  3037.         $entityManager->flush();
  3038.     }
  3039.     }
  3040.         return new Response(json_encode(([
  3041.             "id" => $rdv->getId(),
  3042.             "motif_id" => $rdv->getIdMotif()->getId(),
  3043.             "audio_id" => $rdv->getIdAudio()->getId(),
  3044.             "remplacant_id" => $remplacant_id == -null $remplacant_id,
  3045.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  3046.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  3047.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  3048.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  3049.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  3050.             "testclient" => $rdv->getTestClient() ? [
  3051.                 "result" => $rdv->getTestClient()->getResultTonal(),
  3052.                 "date" => $rdv->getTestClient()->getDate(),
  3053.                 "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  3054.             ] : null,
  3055.             "duration" => $audioMotif->getDuration(),
  3056.             "consigne" => $audioMotif->getConsigne(),
  3057.             "etat_id" => $rdv->getIdEtat()->getId(),
  3058.             "date" => $rdv->getDate(),
  3059.             "comment" => $rdv->getComment(),
  3060.             "centerName" => $rdv->getIdCentre()->getName(),
  3061.             "review" => $rdv->getReview(),
  3062.             "note" => $rdv->getNote(),
  3063.             "status" => 200,
  3064.             "paramsPatient" => $paramsPatient,
  3065.             "isNew" => $isNew,
  3066.         ])));
  3067.     }
  3068.     /**
  3069.      * @Route("/rdv/v2", name="postRdvV2", methods={"POST"})
  3070.      *
  3071.      * Version optimisée de la prise de rendez-vous pour les clients via le site
  3072.      * Gestion complète: validation, création RDV, notifications email/SMS
  3073.      */
  3074.     public function postRdvV2(
  3075.         Request $request,
  3076.         PublicFunction $publicFunction,
  3077.         GoogleCalendarService $googleCalendar,
  3078.         AppointmentCallService $callService
  3079.     ): JsonResponse {
  3080.         try {
  3081.             $data json_decode($request->getContent(), true);
  3082.             // Validation du token et récupération du client
  3083.             $validationResult $this->validateTokenAndGetClient($data);
  3084.             if ($validationResult instanceof Response) {
  3085.                 return new JsonResponse(json_decode($validationResult->getContent(), true), $validationResult->getStatusCode());
  3086.             }
  3087.             ['client' => $client'token' => $token] = $validationResult;
  3088.             // Récupération et validation de l'audio
  3089.             $audio $this->entityManager->getRepository(Audio::class)->find($data['audio_id'] ?? null);
  3090.             if (!$audio) {
  3091.                 return new JsonResponse([
  3092.                     'message' => "Aucun audioprothésiste trouvé avec cet ID.",
  3093.                     'status' => 404
  3094.                 ], 404);
  3095.             }
  3096.             // Vérification du blocage client
  3097.             $clientBlocked $this->entityManager->getRepository(ClientBlocked::class)
  3098.                 ->findOneBy(['id_audio' => $audio'id_client' => $client]);
  3099.             if ($clientBlocked) {
  3100.                 return new JsonResponse([
  3101.                     'message' => 'Vous avez été bloqué par cet audioprothésiste.',
  3102.                     'status' => 403
  3103.                 ], 403);
  3104.             }
  3105.             // Validation du centre/lieu
  3106.             $locationResult $this->validateLocation($data$audio);
  3107.             if ($locationResult instanceof Response) {
  3108.                 return new JsonResponse(json_decode($locationResult->getContent(), true), $locationResult->getStatusCode());
  3109.             }
  3110.             ['centre' => $centre'lieu' => $lieu'liaison' => $liaison] = $locationResult;
  3111.             // Validation du motif
  3112.             $motifResult $this->validateMotif($data$audio);
  3113.             if ($motifResult instanceof Response) {
  3114.                 return new JsonResponse(json_decode($motifResult->getContent(), true), $motifResult->getStatusCode());
  3115.             }
  3116.             ['motif' => $motif'audioMotif' => $audioMotif] = $motifResult;
  3117.             // Validation de la disponibilité
  3118.             $date \DateTime::createFromFormat("d/m/Y H:i"$data['date']);
  3119.             if (!$date) {
  3120.                 return new JsonResponse([
  3121.                     'message' => 'Format de date invalide. Utilisez le format: d/m/Y H:i',
  3122.                     'status' => 400
  3123.                 ], 400);
  3124.             }
  3125.             $availabilityResult $this->validateAvailability(
  3126.                 $audio,
  3127.                 $date,
  3128.                 $audioMotif->getDuration(),
  3129.                 $centre,
  3130.                 $lieu,
  3131.                 $liaison,
  3132.                 $publicFunction
  3133.             );
  3134.             if ($availabilityResult instanceof Response) {
  3135.                 return new JsonResponse(json_decode($availabilityResult->getContent(), true), $availabilityResult->getStatusCode());
  3136.             }
  3137.             $remplacant_id $availabilityResult;
  3138.             // Création du rendez-vous
  3139.             $rdv $this->createAppointment($data$client$audio$centre$lieu$motif$audioMotif$date$remplacant_id);
  3140.             // Envoi des notifications
  3141.             $this->sendNotifications($rdv$client$audio$publicFunction$data);
  3142.             // Synchronisation Google Calendar
  3143.             $this->syncGoogleCalendar($audio$rdv$googleCalendar$data);
  3144.             // Notification call center si nécessaire
  3145.             if (isset($data['isMyaudio']) || isset($data['isRdvLead']) || isset($data['isRdvRapide'])) {
  3146.                 try {
  3147.                     $callService->handleCallCenterAfterRdv($rdv);
  3148.                     $rdv->setIsNotificationRdvCallSent(1);
  3149.                     $this->entityManager->flush();
  3150.                 } catch (\Exception $e) {
  3151.                     $this->logger->error("Erreur notification call center RDV #{$rdv->getId()}: " $e->getMessage());
  3152.                 }
  3153.             }
  3154.             // Réponse finale
  3155.             return new JsonResponse([
  3156.                 'success' => true,
  3157.                 'message' => 'Rendez-vous créé avec succès',
  3158.                 'rdv' => [
  3159.                     'id' => $rdv->getId(),
  3160.                     'date' => $rdv->getDate()->format('d/m/Y H:i'),
  3161.                     'motif' => $motif->getTitre(),
  3162.                     'duration' => $audioMotif->getDuration(),
  3163.                     'centre' => $centre $centre->getName() : null,
  3164.                     'lieu' => $lieu $lieu->getName() : null,
  3165.                     'audio' => $audio->getName() . ' ' $audio->getLastName(),
  3166.                 ],
  3167.                 'status' => 201
  3168.             ], 201);
  3169.         } catch (\Exception $e) {
  3170.             $this->logger->error("Erreur lors de la création du RDV: " $e->getMessage());
  3171.             return new JsonResponse([
  3172.                 'success' => false,
  3173.                 'message' => 'Une erreur est survenue lors de la création du rendez-vous.',
  3174.                 'error' => $e->getMessage(),
  3175.                 'status' => 500
  3176.             ], 500);
  3177.         }
  3178.     }
  3179.     /**
  3180.      * Valide le token et récupère le client associé
  3181.      */
  3182.     private function validateTokenAndGetClient(array $data)
  3183.     {
  3184.         if (!isset($data['token'])) {
  3185.             return new Response(json_encode([
  3186.                 'message' => "Aucun token n'a été spécifié",
  3187.                 'status' => 401
  3188.             ]), 401);
  3189.         }
  3190.         $token $this->entityManager->getRepository(Token::class)
  3191.             ->findOneBy(['token' => $data['token']]);
  3192.         if (!$token) {
  3193.             return new Response(json_encode([
  3194.                 'message' => "Token invalide. Veuillez vous reconnecter.",
  3195.                 'status' => 404
  3196.             ]), 404);
  3197.         }
  3198.         // Vérification de l'âge du token
  3199.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  3200.         if ($dateDiff->7) {
  3201.             $this->entityManager->remove($token);
  3202.             $this->entityManager->flush();
  3203.             return new Response(json_encode([
  3204.                 'message' => 'Token expiré. Veuillez vous reconnecter.',
  3205.                 'status' => 401
  3206.             ]), 401);
  3207.         }
  3208.         // Récupération du client
  3209.         $client $token->getIdClient();
  3210.         if (!$client) {
  3211.             return new Response(json_encode([
  3212.                 'message' => "Ce token n'est pas associé à un client.",
  3213.                 'status' => 400
  3214.             ]), 400);
  3215.         }
  3216.         return ['client' => $client'token' => $token];
  3217.     }
  3218.     /**
  3219.      * Valide le centre ou lieu du rendez-vous
  3220.      */
  3221.     private function validateLocation(array $dataAudio $audio)
  3222.     {
  3223.         $centre null;
  3224.         $lieu null;
  3225.         $liaison null;
  3226.         if (isset($data['centre_id'])) {
  3227.             $centre $this->entityManager->getRepository(Centre::class)->find($data['centre_id']);
  3228.             if (!$centre) {
  3229.                 return new Response(json_encode([
  3230.                     'message' => 'Aucun centre trouvé avec cet ID',
  3231.                     'status' => 404
  3232.                 ]), 404);
  3233.             }
  3234.             $liaison $this->entityManager->getRepository(AudioCentre::class)
  3235.                 ->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
  3236.             if (!$liaison) {
  3237.                 return new Response(json_encode([
  3238.                     'message' => "L'audioprothésiste n'est pas rattaché à ce centre",
  3239.                     'status' => 400
  3240.                 ]), 400);
  3241.             }
  3242.         } elseif (isset($data['lieu_id']) && $audio->getIsIndie()) {
  3243.             $lieu $this->entityManager->getRepository(Lieu::class)
  3244.                 ->findOneBy(['id' => $data['lieu_id'], 'id_gerant' => $audio->getId()]);
  3245.             if (!$lieu) {
  3246.                 return new Response(json_encode([
  3247.                     'message' => 'Aucun lieu trouvé avec cet ID',
  3248.                     'status' => 404
  3249.                 ]), 404);
  3250.             }
  3251.         } else {
  3252.             return new Response(json_encode([
  3253.                 'message' => 'Veuillez spécifier un centre ou un lieu',
  3254.                 'status' => 400
  3255.             ]), 400);
  3256.         }
  3257.         return ['centre' => $centre'lieu' => $lieu'liaison' => $liaison];
  3258.     }
  3259.     /**
  3260.      * Valide le motif du rendez-vous
  3261.      */
  3262.     private function validateMotif(array $dataAudio $audio)
  3263.     {
  3264.         if (!isset($data['motif_id'])) {
  3265.             return new Response(json_encode([
  3266.                 'message' => 'Aucun motif spécifié',
  3267.                 'status' => 400
  3268.             ]), 400);
  3269.         }
  3270.         $motif $this->entityManager->getRepository(Motif::class)->find($data['motif_id']);
  3271.         if (!$motif) {
  3272.             return new Response(json_encode([
  3273.                 'message' => 'Aucun motif trouvé avec cet ID',
  3274.                 'status' => 404
  3275.             ]), 404);
  3276.         }
  3277.         $audioMotif $this->entityManager->getRepository(AudioMotif::class)
  3278.             ->findOneBy(['id_audio' => $audio->getId(), 'id_motif' => $data['motif_id']]);
  3279.         if (!$audioMotif) {
  3280.             return new Response(json_encode([
  3281.                 'message' => "Ce motif n'est pas disponible pour cet audioprothésiste",
  3282.                 'status' => 400
  3283.             ]), 400);
  3284.         }
  3285.         return ['motif' => $motif'audioMotif' => $audioMotif];
  3286.     }
  3287.     /**
  3288.      * Valide la disponibilité du créneau
  3289.      */
  3290.     private function validateAvailability(
  3291.         Audio $audio,
  3292.         \DateTime $date,
  3293.         int $duration,
  3294.         ?Centre $centre,
  3295.         ?Lieu $lieu,
  3296.         ?AudioCentre $liaison,
  3297.         PublicFunction $publicFunction
  3298.     ) {
  3299.         // Vérification qu'il n'y a pas déjà un RDV à cette date
  3300.         $existingRdv $this->entityManager->getRepository(Rdv::class)
  3301.             ->findOneBy([
  3302.                 'date' => $date,
  3303.                 'id_audio' => $audio,
  3304.                 'id_centre' => $centre,
  3305.                 'id_lieu' => $lieu,
  3306.             ]);
  3307.         if ($existingRdv) {
  3308.             return new Response(json_encode([
  3309.                 'message' => 'Un rendez-vous existe déjà à ce créneau',
  3310.                 'status' => 409
  3311.             ]), 409);
  3312.         }
  3313.         // Vérification de la disponibilité selon le type d'audio
  3314.         if ($audio->getIsIndie()) {
  3315.             if ($centre && $liaison) {
  3316.                 if (!$liaison->getHoraire() || $liaison->getHoraire() == []) {
  3317.                     return new Response(json_encode([
  3318.                         'message' => 'Aucun horaire configuré pour cet audioprothésiste',
  3319.                         'status' => 400
  3320.                     ]), 400);
  3321.                 }
  3322.                 if (!$publicFunction->calculScheduleFitDate($audio$date$duration$centre)) {
  3323.                     return new Response(json_encode([
  3324.                         'message' => 'Créneau non disponible',
  3325.                         'status' => 400
  3326.                     ]), 400);
  3327.                 }
  3328.                 return $publicFunction->checkIfRemplacant($liaison->getHoraire(), $date);
  3329.             } else {
  3330.                 if (!$lieu->getHoraire() || $lieu->getHoraire() == []) {
  3331.                     return new Response(json_encode([
  3332.                         'message' => 'Aucun horaire configuré pour ce lieu',
  3333.                         'status' => 400
  3334.                     ]), 400);
  3335.                 }
  3336.                 if (!$publicFunction->calculScheduleFitDate($audio$date$durationnull$lieu)) {
  3337.                     return new Response(json_encode([
  3338.                         'message' => 'Créneau non disponible',
  3339.                         'status' => 400
  3340.                     ]), 400);
  3341.                 }
  3342.                 return $publicFunction->checkIfRemplacant($lieu->getHoraire(), $date);
  3343.             }
  3344.         } else {
  3345.             if (!$liaison || !$liaison->getHoraire() || $liaison->getHoraire() == []) {
  3346.                 return new Response(json_encode([
  3347.                     'message' => 'Aucun horaire configuré',
  3348.                     'status' => 400
  3349.                 ]), 400);
  3350.             }
  3351.             return $publicFunction->checkIfRemplacant($liaison->getHoraire(), $date);
  3352.         }
  3353.     }
  3354.     /**
  3355.      * Crée le rendez-vous en base de données
  3356.      */
  3357.     private function createAppointment(
  3358.         array $data,
  3359.         Client $client,
  3360.         Audio $audio,
  3361.         ?Centre $centre,
  3362.         ?Lieu $lieu,
  3363.         Motif $motif,
  3364.         AudioMotif $audioMotif,
  3365.         \DateTime $date,
  3366.         int $remplacant_id
  3367.     ): Rdv {
  3368.         $rdv = new Rdv();
  3369.         $rdv->setIdClient($client);
  3370.         $rdv->setIdAudio($audio);
  3371.         $rdv->setIdCentre($centre);
  3372.         $rdv->setIdLieu($lieu);
  3373.         $rdv->setIdMotif($motif);
  3374.         $rdv->setDate($date);
  3375.         $rdv->setDateCreation(new \DateTime());
  3376.         // Toujours mettre isMyaudio à true pour les RDV clients via le site
  3377.         $rdv->setIsMyaudio(true);
  3378.         $rdv->setIsRdvLp(isset($data['isRdvLead']));
  3379.         $rdv->setIsRdvRapide(isset($data['isRdvRapide']));
  3380.         $rdv->setIsAbsence(0);
  3381.         $rdv->setCacher(0);
  3382.         // Récupération du dernier test client si disponible
  3383.         $testClient $this->entityManager->getRepository(TestClient::class)
  3384.             ->getLatestTestClient($client);
  3385.         if ($testClient && !$testClient->getRdv()) {
  3386.             $rdv->setTestClient($testClient);
  3387.         }
  3388.         // Gestion proche si spécifié
  3389.         if (isset($data['proche_id'])) {
  3390.             $proche $this->entityManager->getRepository(Proches::class)
  3391.                 ->findOneBy(['id' => $data['proche_id'], 'id_client' => $client]);
  3392.             if ($proche) {
  3393.                 $rdv->setIdProche($proche);
  3394.             }
  3395.         }
  3396.         // Durée : utilise celle du motif par défaut ou celle fournie dans les données
  3397.         $rdv->setDuration($data['duree'] ?? $audioMotif->getDuration());
  3398.         // Couleur personnalisée
  3399.         if (isset($data['color'])) {
  3400.             $rdv->setColor($data['color']);
  3401.         }
  3402.         // Note
  3403.         if (isset($data['note'])) {
  3404.             $rdv->setNote($data['note']);
  3405.         }
  3406.         // État du rendez-vous
  3407.         $etat $this->entityManager->getRepository(EtatRdv::class)
  3408.             ->find($data['etat_id'] ?? 1); // État par défaut : 1
  3409.         if ($etat) {
  3410.             $rdv->setIdEtat($etat);
  3411.         }
  3412.         // Remplaçant si applicable
  3413.         if ($remplacant_id != -1) {
  3414.             $remplacant $this->entityManager->getRepository(Remplacant::class)->find($remplacant_id);
  3415.             if ($remplacant) {
  3416.                 $rdv->setRemplacant($remplacant);
  3417.             }
  3418.         }
  3419.         // Gestion lead
  3420.         if (isset($data['lead'])) {
  3421.             $lead $this->entityManager->getRepository(LeadRdv::class)->find($data['lead']);
  3422.             if ($lead) {
  3423.                 $lead->setRdv($rdv);
  3424.                 $leadStatus $this->entityManager->getRepository(LeadStatus::class)
  3425.                     ->findOneBy(['slug' => 'rdv_valider']);
  3426.                 if ($leadStatus) {
  3427.                     $lead->setLeadStatus($leadStatus);
  3428.                 }
  3429.             }
  3430.         }
  3431.         // Mise à jour du client avec centre et audio
  3432.         $client->setIdCentre($centre);
  3433.         $client->setIdAudio($audio);
  3434.         $this->entityManager->persist($client);
  3435.         $this->entityManager->persist($rdv);
  3436.         $this->entityManager->flush();
  3437.         return $rdv;
  3438.     }
  3439.     /**
  3440.      * Envoie toutes les notifications (email + SMS) au client, audio et admin
  3441.      */
  3442.     private function sendNotifications(Rdv $rdvClient $clientAudio $audioPublicFunction $publicFunction, array $data): void
  3443.     {
  3444.         $date $rdv->getDate();
  3445.         $smsDate $date->format('d-m-Y H:i');
  3446.         $formatter = new IntlDateFormatter(
  3447.             'fr_FR',
  3448.             IntlDateFormatter::FULL,
  3449.             IntlDateFormatter::SHORT,
  3450.             null,
  3451.             IntlDateFormatter::GREGORIAN,
  3452.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  3453.         );
  3454.         $smsDateLongFormat $formatter->format($date);
  3455.         $frenchDate ucfirst(preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat));
  3456.         // === Notification CLIENT ===
  3457.         $this->sendClientNotification($rdv$client$smsDate$smsDateLongFormat$frenchDate$publicFunction$data);
  3458.     
  3459.         // === Notification AUDIO ===
  3460.         if ($audio->getConfirmRdvMail() || $audio->getConfirmRdvSms()) {
  3461.             $this->sendAudioNotification($rdv$client$audio$smsDate$frenchDate$publicFunction$data);
  3462.         }
  3463.         // === Notification ADMIN ===
  3464.         $this->sendAdminNotification($rdv$client$smsDate$frenchDate$publicFunction$data);
  3465.     }
  3466.     /**
  3467.      * Envoie les notifications au client (email + SMS)
  3468.      */
  3469.     private function sendClientNotification(
  3470.         Rdv $rdv,
  3471.         Client $client,
  3472.         string $smsDate,
  3473.         string $smsDateLongFormat,
  3474.         string $frenchDate,
  3475.         PublicFunction $publicFunction,
  3476.         array $data
  3477.     ): void {
  3478.         $centre $rdv->getIdCentre();
  3479.         $params = [
  3480.             'lienModifer' => $_ENV['BASE_client'] . 'mes-rendez-vous',
  3481.             'lienAnnule' => $_ENV['BASE_client'] . 'mes-rendez-vous',
  3482.             'date' => $smsDateLongFormat,
  3483.             'RdvDate' => $smsDateLongFormat,
  3484.             'telCentre' => $centre->getPhone(),
  3485.             'centerName' => $centre->getName(),
  3486.             'prenom' => $client->getName(),
  3487.             'centerAddress' => $centre->getAddress() . ' ' $centre->getPostale() . ' ' $centre->getCity(),
  3488.             'centerPostalCode' => $centre->getPostale(),
  3489.             'motif' => $rdv->getIdMotif()->getTitre(),
  3490.             'centerCity' => $centre->getCity(),
  3491.             'audioName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  3492.             'titre' => 'Votre rendez-vous est validé le ' substr($smsDate010) . ' à ' substr($smsDate1115),
  3493.             'frenchDate' => $frenchDate,
  3494.             'heure' => substr($smsDate1115),
  3495.             'clientEmail' => $client->getMail(),
  3496.             'clientPassword' => $data['passwordGenerated'] ?? null,
  3497.             'modifUrl' => $_ENV['BASE_client'] . 'mes-rendez-vous',
  3498.         ];
  3499.         // Email client
  3500.         $templateId = (isset($data['isLead']) && isset($data['passwordGenerated'])) ? 189 181;
  3501.         $subject '✅ Rendez-vous My Audio confirmé le ' $smsDateLongFormat;
  3502.         $publicFunction->sendEmail(
  3503.             $params,
  3504.             $client->getMail(),
  3505.             $client->getName() . ' ' $client->getLastName(),
  3506.             $subject,
  3507.             $templateId
  3508.         );
  3509.         // envoie au personne de confiance si existe
  3510.         $trustedUser $client->getIdPersonneConfiance();
  3511.         if ($trustedUser !== null && $trustedUser->getMail()) {
  3512.           $trustedEmail $trustedUser->getMail();
  3513.           $publicFunction->sendEmail(
  3514.            $params,
  3515.            $trustedEmail,
  3516.            $trustedUser->getName(),
  3517.            $subject,
  3518.            $templateId
  3519.            );
  3520.         }
  3521.         // Envoie au proche aussi si existe
  3522.         if ($rdv->getIdProche() !== null && $rdv->getIdProche()->getMail()) {
  3523.              $proche $rdv->getIdProche();
  3524.              $procheEmail $proche->getMail();
  3525.           $publicFunction->sendEmail(
  3526.              $params,
  3527.              $procheEmail,
  3528.              $proche->getName(),
  3529.              $subject,
  3530.              $templateId
  3531.           );
  3532.         }
  3533.         // SMS client
  3534.         $smsMessage "Votre RDV est validé le " substr($smsDate010) . " à " substr($smsDate1115) .
  3535.                       ", en cas d'imprévu contactez votre centre " $centre->getPhone() .
  3536.                       " pour modifier votre consultation.\nNe pas répondre.";
  3537.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$smsMessage$client->getPhone());
  3538.     }
  3539.     /**
  3540.      * Envoie les notifications à l'audioprothésiste (email + SMS)
  3541.      */
  3542.     private function sendAudioNotification(
  3543.         Rdv $rdv,
  3544.         Client $client,
  3545.         Audio $audio,
  3546.         string $smsDate,
  3547.         string $frenchDate,
  3548.         PublicFunction $publicFunction,
  3549.         array $data
  3550.     ): void {
  3551.         $responses = [
  3552.             'rangeAge' => $data['rangeAge'] ?? null,
  3553.             'situations' => (isset($data['situations']) && !empty($data['situations'])) ? implode(", "$data['situations']) : null,
  3554.             'equipeAppareil' => $data['equipe'] ?? null,
  3555.             'durationEquipe' => $data['durationEquipe'] ?? null,
  3556.             'bilanAuditif' => $data['bilanAuditif'] ?? null,
  3557.             'ordonance' => $data['ordonnance'] ?? null,
  3558.             'dateOrdonance' => $data['dateOrdonance'] ?? null,
  3559.             'canMove' => $data['canMove'] ?? null,
  3560.         ];
  3561.         $params = [
  3562.             'lienModifer' => $_ENV['BASE_logiciel'] . 'rdv',
  3563.             'lienAnnule' => $_ENV['BASE_logiciel'] . 'rdv',
  3564.             'date' => substr($smsDate010),
  3565.             'heure' => substr($smsDate1115),
  3566.             'audioproName' => $audio->getCivilite() . ' ' $audio->getName() . ' ' $audio->getLastName(),
  3567.             'phone' => $client->getPhone(),
  3568.             'clientCivilite' => $client->getCivilite(),
  3569.             'clientNom' => $client->getLastname(),
  3570.             'clientPrenom' => $client->getName(),
  3571.             'clientPostal' => $client->getPostal(),
  3572.             'clientMail' => $client->getMail(),
  3573.             'clientPhone' => $client->getPhone(),
  3574.             'motif' => $rdv->getIdMotif()->getTitre(),
  3575.             'birthdate' => $client->getBirthdate() ? $client->getBirthdate()->format("d/m/Y") : null,
  3576.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  3577.             'centerName' => $rdv->getIdCentre()->getName(),
  3578.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  3579.             'centerCity' => $rdv->getIdCentre()->getCity(),
  3580.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  3581.             'idPatient' => $client->getId(),
  3582.             'proUrl' => $_ENV['BASE_logiciel'],
  3583.             'frenchDate' => $frenchDate,
  3584.             'responses' => $responses,
  3585.         ];
  3586.         $templateEmail = !empty($data['canMove']) ? 197 182;
  3587.         $mailAudio $audio->getMailNotif() ?? $audio->getMail();
  3588.         $phoneAudio $audio->getPhoneNotif() ?? $audio->getPhone();
  3589.         // Email audio
  3590.         if ($audio->getConfirmRdvMail()) {
  3591.             $subject '✅ Nouveau Rendez-vous My Audio le ' $frenchDate ' à ' substr($smsDate1115);
  3592.             $publicFunction->sendEmail($params$mailAudio$audio->getName() . ' ' $audio->getLastName(), $subject$templateEmail);
  3593.         }
  3594.         // SMS audio
  3595.         if ($audio->getConfirmRdvSms()) {
  3596.             $smsMessage "Vous avez un nouveau RDV le " substr($smsDate010) . " à " substr($smsDate1115) .
  3597.                           ", en cas d'aléas contactez votre patient " $client->getPhone() .
  3598.                           " pour modifier votre consultation.\nNe pas répondre.";
  3599.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$smsMessage$phoneAudio);
  3600.         }
  3601.     }
  3602.     /**
  3603.      * Envoie les notifications à l'admin
  3604.      */
  3605.     private function sendAdminNotification(
  3606.         Rdv $rdv,
  3607.         Client $client,
  3608.         string $smsDate,
  3609.         string $frenchDate,
  3610.         PublicFunction $publicFunction,
  3611.         array $data
  3612.     ): void {
  3613.         $responses = [
  3614.             'rangeAge' => $data['rangeAge'] ?? null,
  3615.             'situations' => (isset($data['situations']) && !empty($data['situations'])) ? implode(", "$data['situations']) : null,
  3616.             'equipeAppareil' => $data['equipe'] ?? null,
  3617.             'durationEquipe' => $data['durationEquipe'] ?? null,
  3618.             'bilanAuditif' => $data['bilanAuditif'] ?? null,
  3619.             'ordonance' => $data['ordonnance'] ?? null,
  3620.             'dateOrdonance' => $data['dateOrdonance'] ?? null,
  3621.             'canMove' => $data['canMove'] ?? null,
  3622.         ];
  3623.         $paramsSourceLead = [
  3624.             'trafficSource' => $data['traffic_source'] ?? null,
  3625.             'articleName' => $data['article_name'] ?? null,
  3626.             'lpVersion' => $data['lp_version'] ?? null,
  3627.         ];
  3628.         $paramsAdmin = [
  3629.             'lienModifer' => $_ENV['BASE_logiciel'] . 'rdv',
  3630.             'lienAnnule' => $_ENV['BASE_logiciel'] . 'rdv',
  3631.             'RdvDate' => substr($smsDate010),
  3632.             'heure' => substr($smsDate1115),
  3633.             'clientMail' => $client->getMail(),
  3634.             'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  3635.             'telClient' => $client->getPhone(),
  3636.             'clientNom' => $client->getLastname(),
  3637.             'clientPrenom' => $client->getName(),
  3638.             'clientCivilite' => $client->getCivilite(),
  3639.             'clientPostal' => $client->getPostal(),
  3640.             'clientPhone' => $client->getPhone(),
  3641.             'motif' => $rdv->getIdMotif()->getTitre(),
  3642.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  3643.             'centerName' => $rdv->getIdCentre()->getName(),
  3644.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  3645.             'centerCity' => $rdv->getIdCentre()->getCity(),
  3646.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  3647.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  3648.             'date' => substr($smsDate010),
  3649.             'urlApi' => $_ENV['BASE_API'],
  3650.             'clientId' => $client->getId(),
  3651.             'centerId' => $rdv->getIdCentre()->getId(),
  3652.             'frenchDate' => $frenchDate,
  3653.             'responses' => $responses,
  3654.             'paramsSourceLead' => $paramsSourceLead,
  3655.         ];
  3656.         $subject 'Nouveau RDV MA | RR - ' $rdv->getIdCentre()->getName();
  3657.         $templateEmail = !empty($data['canMove']) ? 190 183;
  3658.         if (!isset($data['isLead'])) {
  3659.             $publicFunction->sendEmail($paramsAdmin'lead.myaudio@gmail.com''my audio'$subject$templateEmail);
  3660.         }
  3661.         $publicFunction->sendEmail($paramsAdmin'contact@myaudio.fr''my audio'$subject$templateEmail);
  3662.     }
  3663.     /**
  3664.      * Synchronise le rendez-vous avec Google Calendar
  3665.      */
  3666.     private function syncGoogleCalendar(Audio $audioRdv $rdvGoogleCalendarService $googleCalendar, array $data): void
  3667.     {
  3668.         try {
  3669.             $synchronisations $this->entityManager->getRepository(SynchronisationSetting::class)
  3670.                 ->findBy(['audio' => $audio->getId()]);
  3671.             $data['rdv'] = $rdv->getId();
  3672.             foreach ($synchronisations as $synchronisation) {
  3673.                 if (!$synchronisation->getIsDeleted()) {
  3674.                     $googleCalendar->checkAndRefreshAccessToken($synchronisation);
  3675.                     $googleCalendar->createEvent($synchronisation$data);
  3676.                 }
  3677.             }
  3678.         } catch (\Exception $e) {
  3679.             $this->logger->error("Erreur synchronisation Google Calendar pour RDV #{$rdv->getId()}: " $e->getMessage());
  3680.         }
  3681.     }
  3682.     /**
  3683.      * @Route("/rdv/{id}/v2", name="getRdvByIDV2", methods={"GET"})
  3684.      *
  3685.      * Version optimisée de getRdvByID
  3686.      * Retourne les informations complètes d'un rendez-vous
  3687.      */
  3688.     public function getRdvByIDV2(int $idRequest $requestPublicFunction $publicFunction): JsonResponse
  3689.     {
  3690.         try {
  3691.             // Validation du token
  3692.             $token $request->query->get('token');
  3693.             if (!$token) {
  3694.                 return new JsonResponse([
  3695.                     'message' => "Aucun token n'a été spécifié",
  3696.                     'status' => 401
  3697.                 ], 401);
  3698.             }
  3699.             $tokenEntity $this->entityManager->getRepository(Token::class)
  3700.                 ->findOneBy(['token' => $token]);
  3701.             if (!$tokenEntity) {
  3702.                 return new JsonResponse([
  3703.                     'message' => "Token invalide. Veuillez vous reconnecter.",
  3704.                     'status' => 404
  3705.                 ], 404);
  3706.             }
  3707.             // Vérification de l'âge du token
  3708.             $dateDiff $tokenEntity->getCreationDate()->diff(new DateTime());
  3709.             if ($dateDiff->7) {
  3710.                 $this->entityManager->remove($tokenEntity);
  3711.                 $this->entityManager->flush();
  3712.                 return new JsonResponse([
  3713.                     'message' => 'Token expiré. Veuillez vous reconnecter.',
  3714.                     'status' => 401
  3715.                 ], 401);
  3716.             }
  3717.             // Récupération du RDV
  3718.             $rdv $this->entityManager->getRepository(Rdv::class)->find($id);
  3719.             if (!$rdv) {
  3720.                 return new JsonResponse([
  3721.                     'message' => "Aucun rendez-vous trouvé avec cet ID",
  3722.                     'status' => 404
  3723.                 ], 404);
  3724.             }
  3725.             // Vérification des droits d'accès
  3726.             $client $tokenEntity->getIdClient();
  3727.             $audio $tokenEntity->getIdAudio();
  3728.             if ($rdv->getIdClient() != $client && $rdv->getIdAudio() != $audio) {
  3729.                 return new JsonResponse([
  3730.                     'message' => "Vous n'êtes pas autorisé à consulter ce rendez-vous",
  3731.                     'status' => 403
  3732.                 ], 403);
  3733.             }
  3734.             // Construction de la réponse
  3735.             $response $this->buildRdvResponse($rdv$publicFunction);
  3736.             return new JsonResponse([
  3737.                 'success' => true,
  3738.                 'rdv' => $response,
  3739.                 'status' => 200
  3740.             ], 200);
  3741.         } catch (\Exception $e) {
  3742.             $this->logger->error("Erreur lors de la récupération du RDV #{$id}: " $e->getMessage());
  3743.             return new JsonResponse([
  3744.                 'success' => false,
  3745.                 'message' => 'Une erreur est survenue lors de la récupération du rendez-vous.',
  3746.                 'error' => $e->getMessage(),
  3747.                 'status' => 500
  3748.             ], 500);
  3749.         }
  3750.     }
  3751.     /**
  3752.      * Construit la réponse complète pour un rendez-vous
  3753.      */
  3754.     private function buildRdvResponse(Rdv $rdvPublicFunction $publicFunction): array
  3755.     {
  3756.         $rdvCentre $rdv->getIdLieu() ?: $rdv->getIdCentre();
  3757.         $audio $rdv->getIdAudio();
  3758.         $centre $rdv->getIdCentre();
  3759.         // Récupération de la liaison audio-centre
  3760.         $liaison null;
  3761.         if ($centre) {
  3762.             $liaison $this->entityManager->getRepository(AudioCentre::class)
  3763.                 ->findOneBy(['id_audio' => $audio'id_centre' => $centre'isConfirmed' => true]);
  3764.         }
  3765.         // Informations de base du RDV
  3766.         $rdvData = [
  3767.             'id' => $rdv->getId(),
  3768.             'date' => $rdv->getDate()->format('Y-m-d H:i:s'),
  3769.             'dateCreation' => $rdv->getDateCreation() ? $rdv->getDateCreation()->format('Y-m-d H:i:s') : null,
  3770.             'duration' => $rdv->getDuration(),
  3771.             'note' => $rdv->getNote(),
  3772.             'comment' => $rdv->getComment(),
  3773.             'review' => $rdv->getReview(),
  3774.             'isMyaudio' => $rdv->getIsMyaudio(),
  3775.             'isRdvLp' => $rdv->getIsRdvLp(),
  3776.             'isRdvRapide' => $rdv->getIsRdvRapide(),
  3777.             'isAbsence' => $rdv->getIsAbsence(),
  3778.             'motif' => [
  3779.                 'id' => $rdv->getIdMotif()->getId(),
  3780.                 'titre' => $rdv->getIdMotif()->getTitre(),
  3781.             ],
  3782.             'etat' => [
  3783.                 'id' => $rdv->getIdEtat()->getId(),
  3784.                 'libelle' => $rdv->getIdEtat()->getLibelle(),
  3785.             ],
  3786.             'client' => $this->buildClientData($rdv),
  3787.             'proche' => $rdv->getIdProche() ? [
  3788.                 'id' => $rdv->getIdProche()->getId(),
  3789.                 'name' => $rdv->getIdProche()->getName(),
  3790.                 'lastname' => $rdv->getIdProche()->getLastname(),
  3791.             ] : null,
  3792.             'testClient' => $rdv->getTestClient() ? [
  3793.                 'result' => $rdv->getTestClient()->getResultTonal(),
  3794.                 'date' => $rdv->getTestClient()->getDate()->format('Y-m-d H:i:s'),
  3795.                 'device' => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  3796.             ] : null,
  3797.             'audio' => $this->buildAudioData($rdv$publicFunction),
  3798.             'centre' => $this->buildCentreData($rdv$rdvCentre$liaison$publicFunction),
  3799.             'remplacant' => $rdv->getRemplacant() ? [
  3800.                 'id' => $rdv->getRemplacant()->getId(),
  3801.                 'civilite' => $rdv->getRemplacant()->getCivilite(),
  3802.                 'name' => $rdv->getRemplacant()->getName(),
  3803.                 'lastname' => $rdv->getRemplacant()->getLastname(),
  3804.                 'imgUrl' => $rdv->getRemplacant()->getImgUrl(),
  3805.             ] : null,
  3806.         ];
  3807.         return $rdvData;
  3808.     }
  3809.     /**
  3810.      * Construit les données du client
  3811.      */
  3812.     private function buildClientData(Rdv $rdv): ?array
  3813.     {
  3814.         $client $rdv->getIdClient() ?: $rdv->getIdClientTemp();
  3815.         if (!$client) {
  3816.             return null;
  3817.         }
  3818.         return [
  3819.             'id' => $client->getId(),
  3820.             'civilite' => $client->getCivilite(),
  3821.             'name' => $client->getName(),
  3822.             'lastname' => $client->getLastname(),
  3823.             'mail' => $client->getMail(),
  3824.             'phone' => $client->getPhone(),
  3825.             'address' => $client->getAddress(),
  3826.             'postal' => $client->getPostal(),
  3827.             'city' => $client->getCity(),
  3828.             'birthdate' => $client->getBirthdate() ? $client->getBirthdate()->format('Y-m-d') : null,
  3829.         ];
  3830.     }
  3831.     /**
  3832.      * Construit les données de l'audio
  3833.      */
  3834.     private function buildAudioData(Rdv $rdvPublicFunction $publicFunction): array
  3835.     {
  3836.         $audio $rdv->getIdAudio();
  3837.         $remplacant $rdv->getRemplacant();
  3838.         // Récupération des reviews audio
  3839.         $audioRdvs $this->entityManager->getRepository(Rdv::class)
  3840.             ->findBy(['id_audio' => $audio->getId()]);
  3841.         $reviewsAudio array_filter($audioRdvs, function($r) {
  3842.             return $r->getReview() !== null && $r->getComment() !== null;
  3843.         });
  3844.         // Motifs
  3845.         $motifs $this->entityManager->getRepository(AudioMotif::class)
  3846.             ->findBy(['id_audio' => $audio->getId()]);
  3847.         $motifsData array_map(function($motif) {
  3848.             return [
  3849.                 'id' => $motif->getIdMotif()->getId(),
  3850.                 'titre' => $motif->getIdMotif()->getTitre(),
  3851.                 'consigne' => $motif->getConsigne(),
  3852.                 'duration' => $motif->getDuration(),
  3853.             ];
  3854.         }, $motifs);
  3855.         // Spécialités
  3856.         $specialities $this->entityManager->getRepository(AudioSpecialite::class)
  3857.             ->findBy(['id_audio' => $audio->getId()]);
  3858.         $specialitiesData array_map(function($spec) {
  3859.             return [
  3860.                 'id' => $spec->getIdSpecialite()->getId(),
  3861.                 'titre' => $spec->getIdSpecialite()->getLibelle(),
  3862.             ];
  3863.         }, $specialities);
  3864.         return [
  3865.             'id' => $remplacant $remplacant->getId() : $audio->getId(),
  3866.             'civilite' => $remplacant $remplacant->getCivilite() : $audio->getCivilite(),
  3867.             'name' => $remplacant $remplacant->getName() : $audio->getName(),
  3868.             'lastname' => $remplacant $remplacant->getLastname() : $audio->getLastname(),
  3869.             'imgUrl' => $remplacant $remplacant->getImgUrl() : $audio->getImgUrl(),
  3870.             'mail' => $remplacant $remplacant->getMail() : $audio->getMail(),
  3871.             'phone' => $remplacant $remplacant->getPhone() : $audio->getPhone(),
  3872.             'adeli' => $audio->getAdeli(),
  3873.             'pin' => $audio->getPin(),
  3874.             'description' => $audio->getDescription(),
  3875.             'averageRating' => $publicFunction->calculateRating($reviewsAudio),
  3876.             'nbrReview' => count($reviewsAudio),
  3877.             'motifs' => array_values($motifsData),
  3878.             'specialities' => array_values($specialitiesData),
  3879.         ];
  3880.     }
  3881.     /**
  3882.      * Construit les données du centre
  3883.      */
  3884.     private function buildCentreData(Rdv $rdv$rdvCentre, ?AudioCentre $liaisonPublicFunction $publicFunction): array
  3885.     {
  3886.         // Récupération des reviews centre
  3887.         $centreRdvs $this->entityManager->getRepository(Rdv::class)
  3888.             ->findBy($rdv->getIdCentre() ? ['id_centre' => $rdvCentre->getId()] : ['id_lieu' => $rdvCentre->getId()]);
  3889.         $reviewsCentre array_filter($centreRdvs, function($r) {
  3890.             return $r->getReview() !== null && $r->getComment() !== null;
  3891.         });
  3892.         // Accès centre
  3893.         $accessCentre $this->entityManager->getRepository(AccessCentre::class)
  3894.             ->findOneBy($rdv->getIdCentre() ? ['id_centre' => $rdvCentre] : ['id_lieu' => $rdvCentre]);
  3895.         // Prestations
  3896.         if ($rdv->getIdCentre()) {
  3897.             $prestations $this->entityManager->getRepository(CentrePrestation::class)
  3898.                 ->findBy(['id_centre' => $rdvCentre->getId()]);
  3899.         } else {
  3900.             $prestations $this->entityManager->getRepository(LieuPrestation::class)
  3901.                 ->findBy(['id_lieu' => $rdvCentre]);
  3902.         }
  3903.         $prestationsData array_map(function($prest) {
  3904.             return [
  3905.                 'id' => $prest->getIdPrestation()->getId(),
  3906.                 'titre' => $prest->getIdPrestation()->getLibelle(),
  3907.             ];
  3908.         }, $prestations);
  3909.         // Mutuelles (uniquement pour centres)
  3910.         $mutuellesData = [];
  3911.         if ($rdv->getIdCentre()) {
  3912.             $mutuelles $this->entityManager->getRepository(CentreMutuelle::class)
  3913.                 ->findBy(['id_centre' => $rdvCentre]);
  3914.             $mutuellesData array_map(function($mut) {
  3915.                 return [
  3916.                     'id' => $mut->getIdMutuelle()->getId(),
  3917.                     'titre' => $mut->getIdMutuelle()->getLibelle(),
  3918.                 ];
  3919.             }, $mutuelles);
  3920.         }
  3921.         // Tiers
  3922.         if ($rdv->getIdCentre()) {
  3923.             $tiers $this->entityManager->getRepository(CentreTier::class)
  3924.                 ->findBy(['id_centre' => $rdvCentre->getId()]);
  3925.         } else {
  3926.             $tiers $this->entityManager->getRepository(LieuTier::class)
  3927.                 ->findBy(['id_lieu' => $rdvCentre]);
  3928.         }
  3929.         $tiersData array_map(function($tier) {
  3930.             return [
  3931.                 'id' => $tier->getIdTier()->getId(),
  3932.                 'titre' => $tier->getIdTier()->getLibelle(),
  3933.             ];
  3934.         }, $tiers);
  3935.         // Horaire
  3936.         $schedule null;
  3937.         if ($rdv->getIdAudio()->getIsIndie() == false) {
  3938.             $schedule $rdv->getIdCentre() ? $rdv->getIdCentre()->getHoraire() : null;
  3939.         } else {
  3940.             $schedule $rdv->getIdLieu() ? $rdv->getIdLieu()->getHoraire() : ($liaison $liaison->getHoraire() : null);
  3941.         }
  3942.         return [
  3943.             'id' => $rdvCentre->getId(),
  3944.             'audio_id' => $rdvCentre->getIdGerant()->getId(),
  3945.             'name' => $rdvCentre->getName(),
  3946.             'imgUrl' => $rdvCentre->getImgUrl(),
  3947.             'isRdvDomicile' => $rdv->getIdCentre() ? $rdvCentre->getIsRdvDomicile() : $rdv->getIdAudio()->getIsRdvDomicileIndie(),
  3948.             'address' => $rdvCentre->getAddress(),
  3949.             'postal' => $rdvCentre->getPostale(),
  3950.             'city' => $rdvCentre->getCity(),
  3951.             'finess' => $rdvCentre->getFiness(),
  3952.             'siret' => $rdvCentre->getSiret(),
  3953.             'website' => $rdvCentre->getWebsite(),
  3954.             'phone' => $rdvCentre->getPhone(),
  3955.             'isHandicap' => $rdvCentre->getIsHandicap(),
  3956.             'longitude' => $rdvCentre->getLongitude(),
  3957.             'latitude' => $rdvCentre->getLatitude(),
  3958.             'description' => $rdv->getIdCentre() ? $rdv->getIdCentre()->getDescription() : null,
  3959.             'averageRating' => $publicFunction->calculateRating($reviewsCentre),
  3960.             'nbrReview' => count($reviewsCentre),
  3961.             'isLieu' => $rdv->getIdLieu() !== null,
  3962.             'schedule' => $schedule,
  3963.             'access' => $accessCentre ? [
  3964.                 'tram' => $accessCentre->getTram(),
  3965.                 'rer' => $accessCentre->getRer(),
  3966.                 'metro' => $accessCentre->getMetro(),
  3967.                 'bus' => $accessCentre->getBus(),
  3968.                 'parkingPublic' => $accessCentre->getParkingPublic(),
  3969.                 'parkingPrivate' => $accessCentre->getParkingPrivate(),
  3970.                 'other' => $accessCentre->getOther(),
  3971.             ] : null,
  3972.             'prestations' => array_values($prestationsData),
  3973.             'mutuelles' => array_values($mutuellesData),
  3974.             'tiers' => array_values($tiersData),
  3975.         ];
  3976.     }
  3977.     /**
  3978.      * @Route("/rdv/{id}/v2", name="editRdvByIDV2", methods={"PUT", "PATCH"})
  3979.      *
  3980.      * Version optimisée de editRdvByID pour les clients
  3981.      * Gestion complète: modification RDV, notifications email/SMS, Google Calendar
  3982.      */
  3983.     public function editRdvByIDV2(
  3984.         int $id,
  3985.         Request $request,
  3986.         PublicFunction $publicFunction,
  3987.         GoogleCalendarService $googleCalendar
  3988.     ): JsonResponse {
  3989.         try {
  3990.             $data json_decode($request->getContent(), true);
  3991.             // Validation du token et récupération du client
  3992.             $validationResult $this->validateTokenAndGetClient($data);
  3993.             if ($validationResult instanceof Response) {
  3994.                 return new JsonResponse(json_decode($validationResult->getContent(), true), $validationResult->getStatusCode());
  3995.             }
  3996.             ['client' => $client] = $validationResult;
  3997.             // Récupération du RDV
  3998.             $rdv $this->entityManager->getRepository(Rdv::class)->find($id);
  3999.             if (!$rdv) {
  4000.                 return new JsonResponse([
  4001.                     'message' => "Aucun rendez-vous trouvé avec cet ID",
  4002.                     'status' => 404
  4003.                 ], 404);
  4004.             }
  4005.             // Vérification des droits (seulement le client peut modifier son RDV)
  4006.             if ($rdv->getIdClient() != $client) {
  4007.                 return new JsonResponse([
  4008.                     'message' => "Vous n'êtes pas autorisé à modifier ce rendez-vous",
  4009.                     'status' => 403
  4010.                 ], 403);
  4011.             }
  4012.             // Sauvegarde des anciennes valeurs pour les notifications
  4013.             $oldDate $rdv->getDate();
  4014.             $oldDuration $rdv->getDuration();
  4015.             // Traitement de la modification
  4016.             $isModified false;
  4017.             $isCancelled false;
  4018.             // Modification de la date
  4019.             if (isset($data['date'])) {
  4020.                 $newDate \DateTime::createFromFormat("d/m/Y H:i"$data['date']);
  4021.                 if (!$newDate) {
  4022.                     return new JsonResponse([
  4023.                         'message' => 'Format de date invalide. Utilisez le format: d/m/Y H:i',
  4024.                         'status' => 400
  4025.                     ], 400);
  4026.                 }
  4027.                 // Vérification de la disponibilité
  4028.                 $audioMotif $this->entityManager->getRepository(AudioMotif::class)
  4029.                     ->findOneBy(['id_audio' => $rdv->getIdAudio(), 'id_motif' => $rdv->getIdMotif()]);
  4030.                 if (!$audioMotif) {
  4031.                     return new JsonResponse([
  4032.                         'message' => "Le motif n'est plus disponible pour cet audioprothésiste",
  4033.                         'status' => 400
  4034.                     ], 400);
  4035.                 }
  4036.                 // Vérification qu'il n'y a pas déjà un RDV à cette nouvelle date
  4037.                 $existingRdv $this->entityManager->getRepository(Rdv::class)
  4038.                     ->findOneBy([
  4039.                         'date' => $newDate,
  4040.                         'id_audio' => $rdv->getIdAudio(),
  4041.                         'id_centre' => $rdv->getIdCentre(),
  4042.                         'id_lieu' => $rdv->getIdLieu(),
  4043.                     ]);
  4044.                 if ($existingRdv && $existingRdv->getId() !== $rdv->getId()) {
  4045.                     return new JsonResponse([
  4046.                         'message' => 'Un rendez-vous existe déjà à ce créneau',
  4047.                         'status' => 409
  4048.                     ], 409);
  4049.                 }
  4050.                 $rdv->setDateOldRdv($oldDate);
  4051.                 $rdv->setDate($newDate);
  4052.                 $isModified true;
  4053.             }
  4054.             // Modification de la durée
  4055.             if (isset($data['duree']) && $data['duree'] !== $oldDuration) {
  4056.                 $rdv->setDuration($data['duree']);
  4057.                 $isModified true;
  4058.             }
  4059.             // Modification de la note
  4060.             if (isset($data['note'])) {
  4061.                 $rdv->setNote($data['note']);
  4062.             }
  4063.             // Gestion de l'annulation (état 2 = annulé)
  4064.             if (isset($data['etat_id']) && $data['etat_id'] == 2) {
  4065.                 $etat $this->entityManager->getRepository(EtatRdv::class)->find(2);
  4066.                 if ($etat) {
  4067.                     $rdv->setIdEtat($etat);
  4068.                     $isCancelled true;
  4069.                     // Suppression des événements Google Calendar
  4070.                     $this->deleteGoogleCalendarEvents($rdv$googleCalendar);
  4071.                 }
  4072.             }
  4073.             // Persistance des modifications
  4074.             $rdv->setGoogleAgendaImported(false);
  4075.             $this->entityManager->flush();
  4076.             // Envoi des notifications
  4077.             if ($isModified && !$isCancelled) {
  4078.                 $this->sendModificationNotifications($rdv$client$oldDate$publicFunction$data);
  4079.                 $this->updateGoogleCalendarEvents($rdv$googleCalendar$data);
  4080.             } elseif ($isCancelled) {
  4081.                 $this->sendCancellationNotifications($rdv$client$publicFunction$data);
  4082.             }
  4083.             // Réponse
  4084.             return new JsonResponse([
  4085.                 'success' => true,
  4086.                 'message' => $isCancelled 'Rendez-vous annulé avec succès' 'Rendez-vous modifié avec succès',
  4087.                 'rdv' => [
  4088.                     'id' => $rdv->getId(),
  4089.                     'date' => $rdv->getDate()->format('Y-m-d H:i:s'),
  4090.                     'duration' => $rdv->getDuration(),
  4091.                     'note' => $rdv->getNote(),
  4092.                     'etat' => [
  4093.                         'id' => $rdv->getIdEtat()->getId(),
  4094.                         'libelle' => $rdv->getIdEtat()->getLibelle(),
  4095.                     ],
  4096.                 ],
  4097.                 'status' => 200
  4098.             ], 200);
  4099.         } catch (\Exception $e) {
  4100.             $this->logger->error("Erreur lors de la modification du RDV #{$id}: " $e->getMessage());
  4101.             return new JsonResponse([
  4102.                 'success' => false,
  4103.                 'message' => 'Une erreur est survenue lors de la modification du rendez-vous.',
  4104.                 'error' => $e->getMessage(),
  4105.                 'status' => 500
  4106.             ], 500);
  4107.         }
  4108.     }
  4109.     /**
  4110.      * Envoie les notifications de modification de RDV
  4111.      */
  4112.     private function sendModificationNotifications(
  4113.         Rdv $rdv,
  4114.         Client $client,
  4115.         \DateTime $oldDate,
  4116.         PublicFunction $publicFunction,
  4117.         array $data
  4118.     ): void {
  4119.         $date $rdv->getDate();
  4120.         $smsDate $date->format('d-m-Y H:i');
  4121.         $formatter = new IntlDateFormatter(
  4122.             'fr_FR',
  4123.             IntlDateFormatter::FULL,
  4124.             IntlDateFormatter::SHORT,
  4125.             null,
  4126.             IntlDateFormatter::GREGORIAN,
  4127.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  4128.         );
  4129.         $smsDateLongFormat $formatter->format($date);
  4130.         $frenchDate ucfirst(preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat));
  4131.         // Notification CLIENT
  4132.         $paramsClient = [
  4133.             'lienModifer' => $_ENV['BASE_client'] . 'mes-rendez-vous',
  4134.             'lienAnnule' => $_ENV['BASE_client'] . 'mes-rendez-vous',
  4135.             'date' => $smsDateLongFormat,
  4136.             'heure' => substr($smsDate1115),
  4137.             'motif' => $rdv->getIdMotif()->getTitre(),
  4138.             'centerName' => $rdv->getIdCentre()->getName(),
  4139.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4140.             'centerPostalCode' => $rdv->getIdCentre()->getPostale(),
  4141.             'audioMail' => $rdv->getIdAudio()->getMail(),
  4142.             'centerPhone' => $rdv->getIdCentre()->getPhone(),
  4143.             'centerCity' => $rdv->getIdCentre()->getCity(),
  4144.             'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  4145.             'titre' => 'Votre rendez-vous est modifié pour le',
  4146.             'frenchDate' => $frenchDate,
  4147.         ];
  4148.         $subject "🔀 Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  4149.         $publicFunction->sendEmail(
  4150.             $paramsClient,
  4151.             $client->getMail(),
  4152.             $client->getName() . ' ' $client->getLastName(),
  4153.             $subject,
  4154.             184
  4155.         );
  4156.         // envoie au personne de confiance si existe
  4157.         $trustedUser $client->getIdPersonneConfiance();
  4158.         if ($trustedUser !== null && $trustedUser->getMail()) {
  4159.           $trustedEmail $trustedUser->getMail();
  4160.           $publicFunction->sendEmail(
  4161.            $paramsClient,
  4162.            $trustedEmail,
  4163.            $trustedUser->getName(),
  4164.            $subject,
  4165.            184
  4166.            );
  4167.         }
  4168.         // Envoie au proche aussi si existe
  4169.         if ($rdv->getIdProche() !== null && $rdv->getIdProche()->getMail()) {
  4170.              $proche $rdv->getIdProche();
  4171.              $procheEmail $proche->getMail();
  4172.           $publicFunction->sendEmail(
  4173.              $paramsClient,
  4174.              $procheEmail,
  4175.              $proche->getName(),
  4176.              $subject,
  4177.              184
  4178.           );
  4179.         }
  4180.         // SMS client si demandé
  4181.         //if (isset($data['sms']) && $data['sms']) {
  4182.             $smsMessage "Votre RDV est modifié pour le " substr($smsDate010) . " à " substr($smsDate1115) .
  4183.                           ", en cas d'imprévu contactez votre centre " $rdv->getIdCentre()->getPhone() .
  4184.                           " pour modifier votre consultation.\nNe pas répondre.";
  4185.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$smsMessage$client->getPhone());
  4186.         //}
  4187.         // Notification AUDIO
  4188.         $audio $rdv->getIdAudio();
  4189.         if ($audio->getModifRdvMail() || $audio->getModifRdvSms()) {
  4190.             $paramsAudio = [
  4191.                 'lienModifer' => $_ENV['BASE_logiciel'] . 'rdv',
  4192.                 'lienAnnule' => $_ENV['BASE_logiciel'] . 'rdv',
  4193.                 'date' => substr($smsDate010),
  4194.                 'frenchDate' => $frenchDate,
  4195.                 'heure' => substr($smsDate1115),
  4196.                 'motif' => $rdv->getIdMotif()->getTitre(),
  4197.                 'clientPhone' => $client->getPhone(),
  4198.                 'clientNom' => $client->getLastname(),
  4199.                 'clientPrenom' => $client->getName(),
  4200.                 'clientCivilite' => $client->getCivilite(),
  4201.                 'clientPostal' => $client->getPostal(),
  4202.                 'clientMail' => $client->getMail(),
  4203.                 'centerName' => $rdv->getIdCentre()->getName(),
  4204.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4205.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  4206.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4207.                 'idPatient' => $client->getId(),
  4208.                 'proUrl' => $_ENV['BASE_logiciel'],
  4209.                 'audioproName' => $audio->getCivilite() . ' ' $audio->getName() . ' ' $audio->getLastName(),
  4210.                 'titre' => 'Votre rendez-vous est modifié pour le :'
  4211.             ];
  4212.             $mailAudio $audio->getMailNotif() ?? $audio->getMail();
  4213.             if ($audio->getModifRdvMail()) {
  4214.                 $subjectAudio "🔀 Rendez-vous My Audio modifié du " $frenchDate " à " substr($smsDate1115);
  4215.                 $publicFunction->sendEmail($paramsAudio$mailAudio$audio->getName() . ' ' $audio->getLastName(), $subjectAudio186);
  4216.             }
  4217.         }
  4218.     }
  4219.     /**
  4220.      * Envoie les notifications d'annulation de RDV
  4221.      */
  4222.     private function sendCancellationNotifications(
  4223.         Rdv $rdv,
  4224.         Client $client,
  4225.         PublicFunction $publicFunction,
  4226.         array $data
  4227.     ): void {
  4228.         $date $rdv->getDate();
  4229.         $smsDate $date->format('d-m-Y H:i');
  4230.         // Notification CLIENT
  4231.         $paramsClient = [
  4232.             'date' => substr($smsDate010),
  4233.             'lien' => $_ENV['BASE_client'] . 'search',
  4234.             'heure' => substr($smsDate1115),
  4235.             'patientName' => $client->getLastName(),
  4236.             'titre' => 'Votre rendez-vous est annulé :',
  4237.             'centerName' => $rdv->getIdCentre()->getName(),
  4238.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4239.             'centerCity' => $rdv->getIdCentre()->getCity(),
  4240.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4241.             'centerPhone' => $rdv->getIdCentre()->getPhone(),
  4242.             'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  4243.             'audioMail' => $rdv->getIdAudio()->getMail(),
  4244.             'motif' => $rdv->getIdMotif()->getTitre(),
  4245.         ];
  4246.         $subject "❌ Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  4247.         $publicFunction->sendEmail($paramsClient$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject188);
  4248.         // SMS client si demandé
  4249.         //if (isset($data['sms']) && $data['sms']) {
  4250.             $smsMessage "Votre RDV a été annulé, contactez votre centre " $rdv->getIdCentre()->getPhone() .
  4251.                           " pour prendre un autre RDV.\nNe pas répondre.";
  4252.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$smsMessage$client->getPhone());
  4253.        // }
  4254.         // Notification AUDIO
  4255.         $audio $rdv->getIdAudio();
  4256.         if ($audio->getModifRdvMail()) {
  4257.             $paramsAudio = [
  4258.                 'date' => substr($smsDate010),
  4259.                 'lien' => $_ENV['BASE_client'] . 'search',
  4260.                 'heure' => substr($smsDate1115),
  4261.                 'patientName' => $client->getLastName(),
  4262.                 'titre' => 'Votre rendez-vous est annulé :',
  4263.                 'centerName' => $rdv->getIdCentre()->getName(),
  4264.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4265.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  4266.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4267.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  4268.                 'audioproName' => $audio->getCivilite() . ' ' $audio->getName() . ' ' $audio->getLastName(),
  4269.                 'audioMail' => $audio->getMail(),
  4270.                 'motif' => $rdv->getIdMotif()->getTitre(),
  4271.             ];
  4272.             $mailAudio $audio->getMailNotif() ?? $audio->getMail();
  4273.             $subjectAudio "❌ Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  4274.             $publicFunction->sendEmail($paramsAudio$mailAudio$audio->getName() . ' ' $audio->getLastName(), $subjectAudio188);
  4275.         }
  4276.     }
  4277.     /**
  4278.      * Supprime les événements Google Calendar associés au RDV
  4279.      */
  4280.     private function deleteGoogleCalendarEvents(Rdv $rdvGoogleCalendarService $googleCalendar): void
  4281.     {
  4282.         try {
  4283.             $rdvEvents $this->entityManager->getRepository(RdvEvent::class)
  4284.                 ->findBy(['rdv' => $rdv]);
  4285.             foreach ($rdvEvents as $rdvEvent) {
  4286.                 $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  4287.                 $googleCalendar->deleteEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId());
  4288.                 $this->entityManager->remove($rdvEvent);
  4289.             }
  4290.             $this->entityManager->flush();
  4291.         } catch (\Exception $e) {
  4292.             $this->logger->error("Erreur suppression événements Google Calendar pour RDV #{$rdv->getId()}: " $e->getMessage());
  4293.         }
  4294.     }
  4295.     /**
  4296.      * Met à jour les événements Google Calendar
  4297.      */
  4298.     private function updateGoogleCalendarEvents(Rdv $rdvGoogleCalendarService $googleCalendar, array $data): void
  4299.     {
  4300.         try {
  4301.             $rdvEvents $this->entityManager->getRepository(RdvEvent::class)
  4302.                 ->findBy(['rdv' => $rdv]);
  4303.             $data['rdv'] = $rdv->getId();
  4304.             if ($rdv->getIdClient() !== null) {
  4305.                 $data['client_id'] = $rdv->getIdClient()->getId();
  4306.             }
  4307.             foreach ($rdvEvents as $rdvEvent) {
  4308.                 $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  4309.                 $googleCalendar->updateEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
  4310.             }
  4311.         } catch (\Exception $e) {
  4312.             $this->logger->error("Erreur mise à jour événements Google Calendar pour RDV #{$rdv->getId()}: " $e->getMessage());
  4313.         }
  4314.     }
  4315.     /**
  4316.      * @Route("/rdv/{id}/trusteduser", name="contactTrustedUser", methods={"POST"})
  4317.      */
  4318.     public function contactTrustedUser(Request $requestPublicFunction $publicFunction)
  4319.     {
  4320.         $pastDate $rdv->getDate();
  4321.         $data json_decode($request->getContent(), true);
  4322.         $entityManager $this->getDoctrine()->getManager();
  4323.         if (!isset($data["token"])) {
  4324.             return new Response(json_encode([
  4325.                 "message" => "Pas de token n'a été spécifié",
  4326.                 "status" => 401,
  4327.             ]), 401);
  4328.         }
  4329.         /** @var Token */
  4330.         $token $this->getDoctrine()
  4331.             ->getRepository(Token::class)
  4332.             ->findOneBy(['token' => $data["token"]]);
  4333.         if (!$token) {
  4334.             return new Response(json_encode([
  4335.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  4336.                 "status" => 404,
  4337.             ]), 404);
  4338.         }
  4339.         // get token age
  4340.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  4341.         // if the token if older than 7 days
  4342.         if ($dateDiff->7) {
  4343.             $entityManager->remove($token);
  4344.             $entityManager->flush();
  4345.             return $this->json([
  4346.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  4347.                 'path' => 'src/Controller/ClientController.php',
  4348.                 "status" => 401,
  4349.             ], 401);
  4350.         }
  4351.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  4352.             return new Response(json_encode([
  4353.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  4354.                 "status" => 404,
  4355.             ]), 404);
  4356.         }
  4357.         if (isset($data["date"])) {
  4358.             // remove the taken schedule by rdv to make sure there is no overlap
  4359.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4360.             $audioMotif $this->getDoctrine()
  4361.                 ->getRepository(AudioMotif::class)
  4362.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  4363.             if ($audioMotif == null) {
  4364.                 return new Response(json_encode(([
  4365.                     'message' => 'Error, no motif of this id found at this audio',
  4366.                     'path' => 'src/Controller/RdvController.php',
  4367.                     "status" => 400,
  4368.                 ])), 400);
  4369.             }
  4370.             if ($rdv->getIdAudio()->getIsIndie()) {
  4371.                 if ($rdv->getIdCentre()) {
  4372.                     // regular centre audio indie
  4373.                     /** @var AudioCentre */
  4374.                     $liaison $this->getDoctrine()
  4375.                         ->getRepository(AudioCentre::class)
  4376.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  4377.                     if ($liaison == null) {
  4378.                         return new Response(json_encode(([
  4379.                             'message' => 'Error, audio isnt part of the centre',
  4380.                             'path' => 'src/Controller/RdvController.php',
  4381.                             "status" => 400,
  4382.                         ])), 400);
  4383.                     }
  4384.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  4385.                         return new Response(json_encode(([
  4386.                             'message' => 'Error, no horaire found for this audio',
  4387.                             'path' => 'src/Controller/RdvController.php',
  4388.                             "status" => 400,
  4389.                         ])), 400);
  4390.                     }
  4391.                     // if ($publicFunction->calculScheduleFitDate($liaison->getHoraire(), $rdv->getIdAudio(), $date, $audioMotif->getDuration(), $rdv->getIdCentre()) == false) {
  4392.                     //     return new Response(json_encode(([
  4393.                     //         'message' => 'Error, no timestamp found at this time',
  4394.                     //         'path' => 'src/Controller/RdvController.php',
  4395.                     //         "status" => 400,
  4396.                     //     ])),400);
  4397.                     // }
  4398.                 } else {
  4399.                     // lieu audio indie
  4400.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  4401.                         return new Response(json_encode(([
  4402.                             'message' => 'Error, no horaire found for this audio',
  4403.                             'path' => 'src/Controller/RdvController.php',
  4404.                             "status" => 400,
  4405.                         ])), 400);
  4406.                     }
  4407.                     // if ($publicFunction->calculScheduleFitDate($rdv->getIdLieu()->getHoraire(), $rdv->getIdAudio(), $date, $audioMotif->getDuration(), null, $rdv->getIdLieu()) == false) {
  4408.                     //     return new Response(json_encode(([
  4409.                     //         'message' => 'Error, no timestamp found at this time',
  4410.                     //         'path' => 'src/Controller/RdvController.php',
  4411.                     //         "status" => 400,
  4412.                     //     ])),400);
  4413.                     // }
  4414.                 }
  4415.             } else {
  4416.                 // regular centre
  4417.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  4418.                     return new Response(json_encode(([
  4419.                         'message' => 'Error, no horaire found for this audio',
  4420.                         'path' => 'src/Controller/RdvController.php',
  4421.                         "status" => 400,
  4422.                     ])), 400);
  4423.                 }
  4424.                 // if ($publicFunction->calculScheduleFitDate($rdv->getIdCentre()->getHoraire(), $rdv->getIdAudio(), $date, $audioMotif->getDuration(), $rdv->getIdCentre()) == false) {
  4425.                 //     return new Response(json_encode(([
  4426.                 //         'message' => 'Error, no timestamp found at this time',
  4427.                 //         'path' => 'src/Controller/RdvController.php',
  4428.                 //         "status" => 400,
  4429.                 //     ])),400);
  4430.                 // }
  4431.             }
  4432.             $rdv->setDate($date);
  4433.         }
  4434.         $date $rdv->getDate();
  4435.         $smsDate $date->format('d-m-Y H:i');
  4436.         $oldDate $pastDate->format('d-m-Y H:i');
  4437.         $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>");
  4438.         return new Response(json_encode(([
  4439.             "id" => $rdv->getId(),
  4440.             "status" => 200,
  4441.         ])));
  4442.     }
  4443.     /**
  4444.      * @Route("/rdv/{id}", name="editRdvByID", methods={"PUT"})
  4445.      */
  4446.     public function editRdvByID(PublicFunction $publicFunctionRdv $rdvRequest $requestGoogleCalendarService $googleCalendarRdvSmsService $rdvSms): Response
  4447.     {
  4448.         $pastDate $rdv->getDate();
  4449.         $pastDuration $rdv->getDuration();
  4450.         $data json_decode($request->getContent(), true);
  4451.         $entityManager $this->getDoctrine()->getManager();
  4452.         if (!isset($data["token"])) {
  4453.             return new Response(json_encode([
  4454.                 "message" => "Pas de token n'a été spécifié",
  4455.                 "status" => 401,
  4456.             ]), 401);
  4457.         }
  4458.         /** @var Token */
  4459.         $token $this->getDoctrine()
  4460.             ->getRepository(Token::class)
  4461.             ->findOneBy(['token' => $data["token"]]);
  4462.         if (!$token) {
  4463.             return new Response(json_encode([
  4464.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  4465.                 "status" => 404,
  4466.             ]), 404);
  4467.         }
  4468.         // get token age
  4469.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  4470.         // if the token if older than 7 days
  4471.         if ($dateDiff->7) {
  4472.             $entityManager->remove($token);
  4473.             $entityManager->flush();
  4474.             return $this->json([
  4475.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  4476.                 'path' => 'src/Controller/ClientController.php',
  4477.                 "status" => 401,
  4478.             ], 401);
  4479.         }
  4480.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  4481.             return new Response(json_encode([
  4482.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  4483.                 "status" => 404,
  4484.             ]), 404);
  4485.         }
  4486.         if (isset($data["etat_id"])) {
  4487.             $etat $this->getDoctrine()
  4488.                 ->getRepository(EtatRdv::class)
  4489.                 ->findOneBy(['id' => $data["etat_id"]]);
  4490.             if ($etat == null) {
  4491.                 return new Response(json_encode(([
  4492.                     'message' => 'Error, no etat found at this id',
  4493.                     'path' => 'src/Controller/TrustedUserController.php',
  4494.                     "status" => 400,
  4495.                 ])), 400);
  4496.             }
  4497.             $rdv->setIdEtat($etat);
  4498.         }
  4499.         if (isset($data["audio_id"])) {
  4500.             $audio $this->getDoctrine()
  4501.                 ->getRepository(Audio::class)
  4502.                 ->findOneBy(['id' => $data["audio_id"]]);
  4503.             if ($audio == null) {
  4504.                 return new Response(json_encode(([
  4505.                     'message' => 'Error, no audio found at this id',
  4506.                     'path' => 'src/Controller/TrustedUserController.php',
  4507.                     "status" => 400,
  4508.                 ])), 400);
  4509.             }
  4510.             $rdv->setIdAudio($audio);
  4511.         }
  4512.         if (isset($data["motif_id"])) {
  4513.             $motif $this->getDoctrine()
  4514.                 ->getRepository(Motif::class)
  4515.                 ->find($data["motif_id"]);
  4516.             if ($motif == null) {
  4517.                 return new Response(json_encode(([
  4518.                     'message' => 'Error, no motif found at this id',
  4519.                     'path' => 'src/Controller/TrustedUserController.php',
  4520.                     "status" => 400,
  4521.                 ])), 400);
  4522.             }
  4523.             $rdv->setIdMotif($motif);
  4524.         }
  4525.         if (isset($data["client_id"])) {
  4526.             $client $this->getDoctrine()
  4527.                 ->getRepository(Client::class)
  4528.                 ->findOneBy(['id' => $data["client_id"]]);
  4529.             if ($client == null) {
  4530.                 return new Response(json_encode(([
  4531.                     'message' => 'Error, no client found at this id',
  4532.                     'path' => 'src/Controller/TrustedUserController.php',
  4533.                     "status" => 400,
  4534.                 ])), 400);
  4535.             }
  4536.             $rdv->setIdClient($client);
  4537.         }
  4538.         // set client status
  4539.         if (isset($data["client_status_id"])) {
  4540.             $status $this->getDoctrine()
  4541.                 ->getRepository(ClientStatus::class)
  4542.                 ->findOneBy(['id' => $data["client_status_id"]]);
  4543.             if ($status == null) {
  4544.                 return new Response(json_encode(([
  4545.                     'message' => 'Error, no status found at this id',
  4546.                     'path' => 'src/Controller/TrustedUserController.php',
  4547.                     "status" => 400,
  4548.                 ])), 400);
  4549.             }
  4550.             $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  4551.             $client->setClientStatus($status);
  4552.             $client->setLastUpdateStatus(new \DateTimeImmutable);
  4553.         }
  4554.         if (isset($data["date"])) {
  4555.             $submittedDate $data['date'] ?? null;
  4556.             $newDate \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4557.             $currentDate $rdv->getDate();
  4558.             if (!$currentDate || $currentDate->format('d/m/Y H:i') !== $newDate->format('d/m/Y H:i')) {
  4559.                 $rdv->setDateOldRdv($currentDate);
  4560.             }
  4561.             // remove the taken schedule by rdv to make sure there is no overlap
  4562.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4563.             $dateInput \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4564.             $audioMotif $this->getDoctrine()
  4565.                 ->getRepository(AudioMotif::class)
  4566.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  4567.             if ($audioMotif == null) {
  4568.                 return new Response(json_encode(([
  4569.                     'message' => 'Error, no motif of this id found at this audio',
  4570.                     'path' => 'src/Controller/RdvController.php',
  4571.                     "status" => 400,
  4572.                 ])), 400);
  4573.             }
  4574.             if ($rdv->getIdAudio()->getIsIndie()) {
  4575.                 if ($rdv->getIdCentre()) {
  4576.                     // regular centre audio indie
  4577.                     /** @var AudioCentre */
  4578.                     $liaison $this->getDoctrine()
  4579.                         ->getRepository(AudioCentre::class)
  4580.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  4581.                     if ($liaison == null) {
  4582.                         return new Response(json_encode(([
  4583.                             'message' => 'Error, audio isnt part of the centre',
  4584.                             'path' => 'src/Controller/RdvController.php',
  4585.                             "status" => 400,
  4586.                         ])), 400);
  4587.                     }
  4588.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  4589.                         return new Response(json_encode(([
  4590.                             'message' => 'Error, no horaire found for this audio',
  4591.                             'path' => 'src/Controller/RdvController.php',
  4592.                             "status" => 400,
  4593.                         ])), 400);
  4594.                     }
  4595.                 } else {
  4596.                     // lieu audio indie
  4597.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  4598.                         return new Response(json_encode(([
  4599.                             'message' => 'Error, no horaire found for this audio',
  4600.                             'path' => 'src/Controller/RdvController.php',
  4601.                             "status" => 400,
  4602.                         ])), 400);
  4603.                     }
  4604.                 }
  4605.             } else {
  4606.                 // regular centre
  4607.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  4608.                     return new Response(json_encode(([
  4609.                         'message' => 'Error, no horaire found for this audio',
  4610.                         'path' => 'src/Controller/RdvController.php',
  4611.                         "status" => 400,
  4612.                     ])), 400);
  4613.                 }
  4614.             }
  4615.             $rdv->setDate($date);
  4616.         }
  4617.         if (isset($data["comment"]) && $token->getIdClient()) {
  4618.             $rdv->setComment($data["comment"]);
  4619.         }
  4620.         if (isset($data["review"]) && $token->getIdClient()) {
  4621.             $rdv->setReview($data["review"]);
  4622.         }
  4623.         if (isset($data["note"])) {
  4624.             $rdv->setNote($data["note"]);
  4625.         }
  4626.         if (isset($data["duree"])) {
  4627.             $rdv->setDuration($data["duree"]);
  4628.         }
  4629.         ////// SMSEMAIL A décommenter pour activer l'envoi de SMS + MAIL pour modification annulation de RDV, coté audio / client SMSEMAIL ////
  4630.         $date $rdv->getDate();
  4631.         $smsDate $date->format('d-m-Y H:i');
  4632.         $oldDate $pastDate->format('d-m-Y H:i');
  4633.         $locale 'fr_FR';
  4634.         $formatter = new IntlDateFormatter(
  4635.             $locale,
  4636.             IntlDateFormatter::FULL,
  4637.             IntlDateFormatter::SHORT,
  4638.             null,
  4639.             IntlDateFormatter::GREGORIAN,
  4640.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  4641.         );
  4642.         $smsDateLongFormat $formatter->format($date);
  4643.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  4644.         $frenchDate ucfirst($frenchDate);
  4645.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  4646.         // notif client
  4647.         if ($rdv->getIdEtat()->getId() != 2) {
  4648.             if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  4649.                 if ($data["sms"]) {
  4650.                     $params = array(
  4651.                         "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  4652.                         "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  4653.                         "date" => $smsDateLongFormat,
  4654.                         "heure" => substr($smsDate1115),
  4655.                         "motif" => $rdv->getIdMotif()->getTitre(),
  4656.                         "centerName" => $rdv->getIdCentre()->getName(),
  4657.                         "centerAddress" => $rdv->getIdCentre()->getAddress(),
  4658.                         "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  4659.                         "audioMail" => $rdv->getIdAudio()->getMail(),
  4660.                         "centerPhone" => $rdv->getIdCentre()->getPhone(),
  4661.                         "centerCity" => $rdv->getIdCentre()->getCity(),
  4662.                         "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  4663.                         'titre' => 'Votre rendez-vous est modifié pour le',
  4664.                         'frenchDate' => $frenchDate,
  4665.                     );
  4666.                     $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  4667.                     $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject184);
  4668.                     $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.";
  4669.                     $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  4670.                 }
  4671.             }
  4672.         }
  4673.         //     //// == suppression
  4674.         else if ($rdv->getIdEtat()->getId() == 2) {
  4675.             // delete google agenda event
  4676.             $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  4677.                 ->findBy(array('rdv' => $rdv));
  4678.             foreach ($rdvEvents as $rdvEvent) {
  4679.                 $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  4680.                 if ($googleCalendar) {
  4681.                     $googleCalendar->deleteEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId());
  4682.                     $entityManager->remove($rdvEvent);
  4683.                     $entityManager->flush();
  4684.                 }
  4685.             }
  4686.             //if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  4687.             //if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {                   
  4688.             $params = array(
  4689.                 "date" => substr($smsDate010),
  4690.                 "lien" => "{$_ENV['BASE_client']}search",
  4691.                 "heure" => substr($smsDate1115),
  4692.                 "patientName" => $client->getLastName(),
  4693.                 'titre' => 'Votre rendez-vous est annulé :',
  4694.                 'centerName' => $rdv->getIdCentre()->getName(),
  4695.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4696.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  4697.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4698.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  4699.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  4700.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  4701.                 'motif' => $rdv->getIdMotif()->getTitre(),
  4702.             );
  4703.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  4704.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject188);
  4705.             if ($data["sms"]) {
  4706.                 $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  4707.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  4708.             }
  4709.             //}
  4710.         }
  4711.         // set center
  4712.         if (isset($data["centre_id"])) {
  4713.             $entityManager $this->getDoctrine()->getManager();
  4714.             $centreId $data["centre_id"];
  4715.             $centre $entityManager->getRepository(Centre::class)->find($centreId);
  4716.             if (!$centre) {
  4717.                 return $this->json([
  4718.                     'message' => 'Error, no Centre found with this ID',
  4719.                     'path' => 'src/Controller/YourController.php',
  4720.                 ]);
  4721.             }
  4722.             $rdv->setIdCentre($centre);
  4723.         }
  4724.         $rdv->setGoogleAgendaImported(false);
  4725.         //notif Audio
  4726.         if ($rdv->getIdEtat()->getId() != 2) {
  4727.             if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  4728.                 if ($data["sms"]) {
  4729.                     $params = array(
  4730.                         "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  4731.                         "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  4732.                         "date" => substr($smsDate010),
  4733.                         "frenchDate" => $frenchDate,
  4734.                         "heure" => substr($smsDate1115),
  4735.                         'motif' => $rdv->getIdMotif()->getTitre(),
  4736.                         'clientPhone' => $client->getPhone(),
  4737.                         'clientNom' => $client->getLastname(),
  4738.                         'clientPrenom' => $client->getName(),
  4739.                         'clientCivilite' => $client->getCivilite(),
  4740.                         'clientPostal' => $client->getPostal(),
  4741.                         'clientMail' => $client->getMail(),
  4742.                         'centerName' => $rdv->getIdCentre()->getName(),
  4743.                         'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4744.                         'centerCity' => $rdv->getIdCentre()->getCity(),
  4745.                         'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4746.                         'idPatient' => $client->getId(),
  4747.                         'proUrl' => "{$_ENV['BASE_logiciel']}",
  4748.                         'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  4749.                         'titre' => 'Votre rendez-vous est modifié pour le :'
  4750.                     );
  4751.                     $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  4752.                     $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  4753.                     if ($rdv->getIdAudio()->getModifRdvMail()) {
  4754.                         $subject "🔀 Rendez-vous My Audio modifié du " $frenchDate " à " substr($smsDate1115);
  4755.                         $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject186);
  4756.                     }
  4757.                     if ($rdv->getIdAudio()->getModifRdvSms()) {
  4758.                         // we ignore the sms send to the audio for the case he modify the rdv (so lets commented)
  4759.                         $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.";
  4760.                         //$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $phoneAudio);
  4761.                     }
  4762.                 }
  4763.             }
  4764.         } else if ($rdv->getIdEtat()->getId() == 2) {
  4765.             if ($data["sms"]) {
  4766.                 $params = array(
  4767.                     "date" => substr($smsDate010),
  4768.                     "lien" => "{$_ENV['BASE_client']}search",
  4769.                     "heure" => substr($smsDate1115),
  4770.                     "patientName" => $client->getLastName(),
  4771.                     'titre' => 'Votre rendez-vous est annulé :',
  4772.                     'centerName' => $rdv->getIdCentre()->getName(),
  4773.                     'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4774.                     'centerCity' => $rdv->getIdCentre()->getCity(),
  4775.                     'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4776.                     'centerPhone' => $rdv->getIdCentre()->getPhone(),
  4777.                     'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  4778.                     'audioMail' => $rdv->getIdAudio()->getMail(),
  4779.                     'motif' => $rdv->getIdMotif()->getTitre(),
  4780.                 );
  4781.                 $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  4782.                 $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  4783.                 if ($rdv->getIdAudio()->getModifRdvMail()) {
  4784.                     $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  4785.                     $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject188);
  4786.                 }
  4787.                 if ($rdv->getIdAudio()->getModifRdvSms()) {
  4788.                     $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.";
  4789.                     // $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $phoneAudio);
  4790.                 }
  4791.             }
  4792.         }
  4793.         $entityManager->flush();
  4794.         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"]))) {
  4795.             if (is_null($rdv->getIdClientTemp())) {
  4796.                 $clientRDV $this->getDoctrine()
  4797.                     ->getRepository(Client::class)
  4798.                     ->findOneBy(['id' => $rdv->getIdClient()->getId()]);
  4799.                 $clientRDV->setName($data["prenom_patient"]);
  4800.                 $clientRDV->setLastname($data["nom_patient"]);
  4801.                 $clientRDV->setMail($data["mail_patient"]);
  4802.                 $clientRDV->setPhone($data["portable_patient"]);
  4803.                 $clientRDV->setPhoneFixe($data["fixe_patient"]);
  4804.             } else {
  4805.                 $clientRDV $this->getDoctrine()
  4806.                     ->getRepository(ClientTemp::class)
  4807.                     ->findOneBy(['id' => $rdv->getIdClientTemp()->getId()]);
  4808.                 $clientRDV->setName($data["prenom_patient"]);
  4809.                 $clientRDV->setLastname($data["nom_patient"]);
  4810.                 $clientRDV->setMail($data["mail_patient"]);
  4811.                 $clientRDV->setPhone($data["portable_patient"]);
  4812.                 $clientRDV->setPhoneFixe($data["fixe_patient"]);
  4813.             }
  4814.             if (!empty($data["birthday_patient"])) {
  4815.                 $birth \DateTime::createFromFormat("Y-m-d"$data["birthday_patient"]);
  4816.                 $clientRDV->setBirthdate($birth);
  4817.             }
  4818.             $entityManager->flush();
  4819.         }
  4820.         if (is_null($rdv->getIdClient())) {
  4821.             $prenom_patient $rdv->getIdClientTemp()->getName();
  4822.             $nom_patient $rdv->getIdClientTemp()->getLastname();
  4823.             $mail_patient $rdv->getIdClientTemp()->getMail();
  4824.             $portable_patient $rdv->getIdClientTemp()->getPhone();
  4825.             $fixe_patient $rdv->getIdClientTemp()->getPhoneFixe();
  4826.             $birthday $rdv->getIdClientTemp()->getBirthdate();
  4827.         } elseif (is_null($rdv->getIdClientTemp())) {
  4828.             $prenom_patient =  $rdv->getIdClient()->getName();
  4829.             $nom_patient $rdv->getIdClient()->getLastname();
  4830.             $mail_patient $rdv->getIdClient()->getMail();
  4831.             $portable_patient $rdv->getIdClient()->getPhone();
  4832.             $fixe_patient $rdv->getIdClient()->getPhoneFixe();
  4833.             $birthday $rdv->getIdClient()->getBirthdate();
  4834.         } else {
  4835.             $prenom_patient "";
  4836.             $nom_patient "";
  4837.             $mail_patient "";
  4838.             $portable_patient "";
  4839.             $fixe_patient "";
  4840.             $birthday "";
  4841.         }
  4842.         /* generate sms notif on update */
  4843.         // update sms notification     
  4844.         $rdvSms->updateRdvSms($rdv);
  4845.         // google calendar update
  4846.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  4847.             ->findBy(array('audio' => $rdv->getIdAudio()));
  4848.         $data['rdv'] = $rdv->getId();
  4849.         if ($rdv->getIdClient() !== null) {
  4850.             $data["client_id"] = $rdv->getIdClient()->getId();
  4851.         }
  4852.         if ($rdv->getIdClientTemp() !== null) {
  4853.             $data["client_id_temp"] = $rdv->getIdClientTemp()->getId();
  4854.         }
  4855.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  4856.             ->findBy(array('rdv' => $rdv));
  4857.         foreach ($rdvEvents as $rdvEvent) {
  4858.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  4859.             $googleCalendar->updateEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
  4860.         }
  4861.         $synchronisationCosium $this->getDoctrine()->getRepository(SynchronisationCosium::class)->findOneBy(["audio" => $rdv->getIdAudio()->getId()]);
  4862.         $cosiumCenter $this->getDoctrine()->getRepository(CosiumCenter::class)->findOneBy(["synchronisationCosium" => $synchronisationCosium"center" => $rdv->getIdCentre()]);
  4863.         if ($cosiumCenter) {
  4864.             $this->clientCosiumService->deleteRdv($synchronisationCosium$rdv);
  4865.             $this->clientCosiumService->createAgenda($synchronisationCosium$rdv$cosiumCenter);
  4866.         }
  4867.         $token $this->entityManager
  4868.              ->getRepository(Token::class)
  4869.              ->findOneBy(['token' => $data['token']]);
  4870.         $tokenAudioId $token->getIdAudio()->getId();
  4871.         $requestAudioId $data['audio_id'] ?? null;
  4872.         if ($requestAudioId && $requestAudioId == $tokenAudioId) {
  4873.         // After successfully updating the RDV
  4874.         $this->mercure->publishRdvUpdate($rdv'updated');
  4875.         }
  4876.         return new Response(json_encode(([
  4877.             "id" => $rdv->getId(),
  4878.             "motif_id" => $rdv->getIdMotif()->getId(),
  4879.             "motif_libelle" => $rdv->getIdMotif()->getTitre(),
  4880.             "audio_id" => $rdv->getIdAudio()->getId(),
  4881.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  4882.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  4883.             "fullName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  4884.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  4885.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  4886.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  4887.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  4888.             "centre_name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : null,
  4889.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  4890.             "etat_id" => $rdv->getIdEtat()->getId(),
  4891.             "date" => $rdv->getDate(),
  4892.             "comment" => $rdv->getComment(),
  4893.             "note" => $rdv->getNote(),
  4894.             "review" => $rdv->getReview(),
  4895.             "clientEtatId" => $client->getClientStatus() ? $client->getClientStatus()->getId() : 0,
  4896.             "prenom_patient" => $prenom_patient,
  4897.             "nom_patient" => $nom_patient,
  4898.             "mail_patient" => $mail_patient,
  4899.             "portable_patient" => $portable_patient,
  4900.             "fixe_patient" => $fixe_patient,
  4901.             "birthday" => $birthday,
  4902.             "status" => 200,
  4903.         ])));
  4904.     }
  4905.     /**
  4906.      * @Route("/rdv-by-patient/{id}", name="editRdvByIDFromPatient", methods={"PUT"})
  4907.      */
  4908.     public function editRdvByIDFromPatient(PublicFunction $publicFunctionRdv $rdvRequest $request): Response
  4909.     {
  4910.         $pastDate $rdv->getDate();
  4911.         $pastDuration $rdv->getDuration();
  4912.         $data json_decode($request->getContent(), true);
  4913.         $entityManager $this->getDoctrine()->getManager();
  4914.         if (!isset($data["token"])) {
  4915.             return new Response(json_encode([
  4916.                 "message" => "Pas de token n'a été spécifié",
  4917.                 "status" => 401,
  4918.             ]), 401);
  4919.         }
  4920.         /** @var Token */
  4921.         $token $this->getDoctrine()
  4922.             ->getRepository(Token::class)
  4923.             ->findOneBy(['token' => $data["token"]]);
  4924.         if (!$token) {
  4925.             return new Response(json_encode([
  4926.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  4927.                 "status" => 404,
  4928.             ]), 404);
  4929.         }
  4930.         // get token age
  4931.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  4932.         // if the token if older than 7 days
  4933.         if ($dateDiff->7) {
  4934.             $entityManager->remove($token);
  4935.             $entityManager->flush();
  4936.             return $this->json([
  4937.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  4938.                 'path' => 'src/Controller/ClientController.php',
  4939.                 "status" => 401,
  4940.             ], 401);
  4941.         }
  4942.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  4943.             return new Response(json_encode([
  4944.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  4945.                 "status" => 404,
  4946.             ]), 404);
  4947.         }
  4948.         if (isset($data["etat_id"])) {
  4949.             $etat $this->getDoctrine()
  4950.                 ->getRepository(EtatRdv::class)
  4951.                 ->findOneBy(['id' => $data["etat_id"]]);
  4952.             if ($etat == null) {
  4953.                 return new Response(json_encode(([
  4954.                     'message' => 'Error, no etat found at this id',
  4955.                     'path' => 'src/Controller/TrustedUserController.php',
  4956.                     "status" => 400,
  4957.                 ])), 400);
  4958.             }
  4959.             $rdv->setIdEtat($etat);
  4960.         }
  4961.         if (isset($data["audio_id"])) {
  4962.             $audio $this->getDoctrine()
  4963.                 ->getRepository(Audio::class)
  4964.                 ->findOneBy(['id' => $data["audio_id"]]);
  4965.             if ($audio == null) {
  4966.                 return new Response(json_encode(([
  4967.                     'message' => 'Error, no audio found at this id',
  4968.                     'path' => 'src/Controller/TrustedUserController.php',
  4969.                     "status" => 400,
  4970.                 ])), 400);
  4971.             }
  4972.             $rdv->setIdAudio($audio);
  4973.         }
  4974.         if (isset($data["motif_id"])) {
  4975.             $motif $this->getDoctrine()
  4976.                 ->getRepository(Motif::class)
  4977.                 ->find($data["motif_id"]);
  4978.             if ($motif == null) {
  4979.                 return new Response(json_encode(([
  4980.                     'message' => 'Error, no motif found at this id',
  4981.                     'path' => 'src/Controller/TrustedUserController.php',
  4982.                     "status" => 400,
  4983.                 ])), 400);
  4984.             }
  4985.             $rdv->setIdMotif($motif);
  4986.         }
  4987.         if (isset($data["client_id"])) {
  4988.             $client $this->getDoctrine()
  4989.                 ->getRepository(Client::class)
  4990.                 ->findOneBy(['id' => $data["client_id"]]);
  4991.             if ($client == null) {
  4992.                 return new Response(json_encode(([
  4993.                     'message' => 'Error, no client found at this id',
  4994.                     'path' => 'src/Controller/TrustedUserController.php',
  4995.                     "status" => 400,
  4996.                 ])), 400);
  4997.             }
  4998.             $rdv->setIdClient($client);
  4999.         }
  5000.         if (isset($data["date"])) {
  5001.             // remove the taken schedule by rdv to make sure there is no overlap
  5002.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  5003.             $dateInput \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  5004.             $audioMotif $this->getDoctrine()
  5005.                 ->getRepository(AudioMotif::class)
  5006.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  5007.             if ($audioMotif == null) {
  5008.                 return new Response(json_encode(([
  5009.                     'message' => 'Error, no motif of this id found at this audio',
  5010.                     'path' => 'src/Controller/RdvController.php',
  5011.                     "status" => 400,
  5012.                 ])), 400);
  5013.             }
  5014.             if ($rdv->getIdAudio()->getIsIndie()) {
  5015.                 if ($rdv->getIdCentre()) {
  5016.                     // regular centre audio indie
  5017.                     /** @var AudioCentre */
  5018.                     $liaison $this->getDoctrine()
  5019.                         ->getRepository(AudioCentre::class)
  5020.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  5021.                     if ($liaison == null) {
  5022.                         return new Response(json_encode(([
  5023.                             'message' => 'Error, audio isnt part of the centre',
  5024.                             'path' => 'src/Controller/RdvController.php',
  5025.                             "status" => 400,
  5026.                         ])), 400);
  5027.                     }
  5028.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  5029.                         return new Response(json_encode(([
  5030.                             'message' => 'Error, no horaire found for this audio',
  5031.                             'path' => 'src/Controller/RdvController.php',
  5032.                             "status" => 400,
  5033.                         ])), 400);
  5034.                     }
  5035.                 } else {
  5036.                     // lieu audio indie
  5037.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  5038.                         return new Response(json_encode(([
  5039.                             'message' => 'Error, no horaire found for this audio',
  5040.                             'path' => 'src/Controller/RdvController.php',
  5041.                             "status" => 400,
  5042.                         ])), 400);
  5043.                     }
  5044.                 }
  5045.             } else {
  5046.                 // regular centre
  5047.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  5048.                     return new Response(json_encode(([
  5049.                         'message' => 'Error, no horaire found for this audio',
  5050.                         'path' => 'src/Controller/RdvController.php',
  5051.                         "status" => 400,
  5052.                     ])), 400);
  5053.                 }
  5054.             }
  5055.             $rdv->setDate($date);
  5056.         }
  5057.         if (isset($data["comment"]) && $token->getIdClient()) {
  5058.             $rdv->setComment($data["comment"]);
  5059.         }
  5060.         if (isset($data["review"]) && $token->getIdClient()) {
  5061.             $rdv->setReview($data["review"]);
  5062.         }
  5063.         if (isset($data["note"])) {
  5064.             $rdv->setNote($data["note"]);
  5065.         }
  5066.         if (isset($data["duree"])) {
  5067.             $rdv->setDuration($data["duree"]);
  5068.         }
  5069.         ////// SMSEMAIL A décommenter pour activer l'envoi de SMS + MAIL pour modification annulation de RDV, coté audio / client SMSEMAIL ////
  5070.         $date $rdv->getDate();
  5071.         $smsDate $date->format('d-m-Y H:i');
  5072.         $oldDate $pastDate->format('d-m-Y H:i');
  5073.         $locale 'fr_FR';
  5074.         $formatter = new IntlDateFormatter(
  5075.             $locale,
  5076.             IntlDateFormatter::FULL,
  5077.             IntlDateFormatter::SHORT,
  5078.             null,
  5079.             IntlDateFormatter::GREGORIAN,
  5080.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  5081.         );
  5082.         $smsDateLongFormat $formatter->format($date);
  5083.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  5084.         $frenchDate ucfirst($frenchDate);
  5085.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  5086.         // notif client
  5087.         if ($rdv->getIdEtat()->getId() != 2) {
  5088.             if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  5089.                 $params = array(
  5090.                     "lienModifier" => "{$_ENV['BASE_client']}mes-rendez-vous",
  5091.                     "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  5092.                     "date" => $smsDateLongFormat,
  5093.                     "heure" => substr($smsDate1115),
  5094.                     "motif" => $rdv->getIdMotif()->getTitre(),
  5095.                     "centerName" => $rdv->getIdCentre()->getName(),
  5096.                     "centerAddress" => $rdv->getIdCentre()->getAddress(),
  5097.                     "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  5098.                     "audioMail" => $rdv->getIdAudio()->getMail(),
  5099.                     "centerPhone" => $rdv->getIdCentre()->getPhone(),
  5100.                     "centerCity" => $rdv->getIdCentre()->getCity(),
  5101.                     "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  5102.                     'titre' => 'Votre rendez-vous est modifié pour le',
  5103.                     'frenchDate' => $frenchDate,
  5104.                 );
  5105.                 $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  5106.                 $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject184);
  5107.                 $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.";
  5108.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  5109.             }
  5110.         }
  5111.         //     //// == suppression
  5112.         else if ($rdv->getIdEtat()->getId() == 2) {
  5113.             //if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  5114.             //if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {                   
  5115.             $params = array(
  5116.                 "date" => substr($smsDate010),
  5117.                 "lien" => "{$_ENV['BASE_client']}audioprothesiste/{$rdv->getIdCentre()->getCity()}/{$rdv->getIdCentre()->getPostale()}/{$rdv->getIdCentre()->getName()}/prise-de-rdv-audioprothesiste-rapide/{$rdv->getIdCentre()->getId()}",
  5118.                 "heure" => substr($smsDate1115),
  5119.                 "patientName" => $client->getLastName(),
  5120.                 'titre' => 'Votre rendez-vous est annulé :',
  5121.                 'centerName' => $rdv->getIdCentre()->getName(),
  5122.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  5123.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  5124.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  5125.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  5126.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  5127.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  5128.                 'motif' => $rdv->getIdMotif()->getTitre(),
  5129.             );
  5130.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  5131.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject203);
  5132.             $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  5133.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  5134.             //}
  5135.         }
  5136.         // set center
  5137.         if (isset($data["centre_id"])) {
  5138.             $entityManager $this->getDoctrine()->getManager();
  5139.             $centreId $data["centre_id"];
  5140.             $centre $entityManager->getRepository(Centre::class)->find($centreId);
  5141.             if (!$centre) {
  5142.                 return $this->json([
  5143.                     'message' => 'Error, no Centre found with this ID',
  5144.                     'path' => 'src/Controller/YourController.php',
  5145.                 ]);
  5146.             }
  5147.             $rdv->setIdCentre($centre);
  5148.         }
  5149.         $rdv->setGoogleAgendaImported(false);
  5150.         //notif Audio
  5151.         if ($rdv->getIdEtat()->getId() != 2) {
  5152.             if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  5153.                 $params = array(
  5154.                     "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  5155.                     "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  5156.                     "date" => $pastDate->format("y-m-d"),
  5157.                     "heure" => $pastDate->format("H:i"),
  5158.                     'clientPhone' => $client->getPhone(),
  5159.                     'clientCivilite' => $client->getCivilite(),
  5160.                     'clientNom' => $client->getLastname(),
  5161.                     'clientPrenom' => $client->getName(),
  5162.                     'clientPostal' => $client->getPostal(),
  5163.                     'clientMail' => $client->getMail(),
  5164.                     "birthdate" => $rdv->getIdClient()->getBirthdate()->format("y-m-d"),
  5165.                     "mail" => $rdv->getIdClient()->getMail(),
  5166.                     "phone" => $rdv->getIdClient()->getPhone(),
  5167.                     "motif" => $rdv->getIdMotif()->getTitre(),
  5168.                     "address" => $rdv->getIdCentre()->getAddress(),
  5169.                     "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getLastName() . ' ' $rdv->getIdAudio()->getName(),
  5170.                     "newRdvDate" => substr($smsDate010),
  5171.                     "newRdvHour" => substr($smsDate1115),
  5172.                     "centerName" => $rdv->getIdCentre()->getName(),
  5173.                     "centerAddress" => $rdv->getIdCentre()->getAddress(),
  5174.                     "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  5175.                     'titre' => "Modification de Rendez-vous My Audio de {$rdv->getIdClient()->getLastname()}",
  5176.                     "urlPro" => "{$_ENV['BASE_logiciel']}",
  5177.                     "idPatient" => $rdv->getIdClient()->getId(),
  5178.                 );
  5179.                 $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  5180.                 $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  5181.                 if ($rdv->getIdAudio()->getModifRdvMail()) {
  5182.                     $subject "🔀 Rendez-vous My Audio modifié par " $client->getCivilite() . " " $client->getName() . " " $client->getLastname();
  5183.                     $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject185);
  5184.                 }
  5185.                 $subjectMyAudio "🔀 Le patient " $client->getCivilite() . " " $client->getName() . " " $client->getLastname() . "  a modifié son rendez-vous My Audio";
  5186.                 $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subjectMyAudio204);
  5187.                 if ($rdv->getIdAudio()->getModifRdvSms()) {
  5188.                     $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.";
  5189.                     $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  5190.                 }
  5191.             }
  5192.         } else if ($rdv->getIdEtat()->getId() == 2) {
  5193.             $params = array(
  5194.                 "date" => substr($smsDate010),
  5195.                 "heure" => substr($smsDate1115),
  5196.                 "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  5197.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  5198.                 "motif" => $rdv->getIdMotif()->getTitre(),
  5199.                 "centerAddress" => $rdv->getIdCentre()->getAddress(),
  5200.                 "centerPostal" => $rdv->getIdCentre()->getPostale(),
  5201.                 "centerCity" => $rdv->getIdCentre()->getCity(),
  5202.                 "centerName" => $rdv->getIdCentre()->getName(),
  5203.                 "clientNom" => $rdv->getIdClient()->getLastname(),
  5204.                 "clientPrenom" => $rdv->getIdClient()->getName(),
  5205.                 "clientMail" => $rdv->getIdClient()->getMail(),
  5206.                 "clientPhone" => $rdv->getIdClient()->getPhone(),
  5207.                 'titre' => "Annulation du Rendez-vous avec le patient {$rdv->getIdClient()->getLastname()}",
  5208.                 "proUrl" => "{$_ENV['BASE_logiciel']}",
  5209.                 "idPatient" => $rdv->getIdClient()->getId(),
  5210.             );
  5211.             $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  5212.             $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  5213.             if ($rdv->getIdAudio()->getModifRdvMail()) {
  5214.                 $subject "❌ Annulation du rendez-vous par le patient " $client->getCivilite() . " " $client->getName() . " " $client->getLastname();
  5215.                 $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject187);
  5216.             }
  5217.             $subject "❌ Annulation du rendez-vous par le patient " $client->getCivilite() . " " $client->getName() . " " $client->getLastname();
  5218.             $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject195);
  5219.             if ($rdv->getIdAudio()->getModifRdvSms()) {
  5220.                 $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.";
  5221.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  5222.             }
  5223.         }
  5224.         $entityManager->flush();
  5225.         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"]))) {
  5226.             $birth \DateTime::createFromFormat("Y-m-d"$data["birthday_patient"]);
  5227.             if (is_null($rdv->getIdClientTemp())) {
  5228.                 $clientRDV $this->getDoctrine()
  5229.                     ->getRepository(Client::class)
  5230.                     ->findOneBy(['id' => $rdv->getIdClient()->getId()]);
  5231.                 $clientRDV->setName($data["prenom_patient"]);
  5232.                 $clientRDV->setLastname($data["nom_patient"]);
  5233.                 $clientRDV->setBirthdate($birth);
  5234.                 $clientRDV->setMail($data["mail_patient"]);
  5235.                 $clientRDV->setPhone($data["portable_patient"]);
  5236.                 $clientRDV->setPhoneFixe($data["fixe_patient"]);
  5237.             } else {
  5238.                 $clientRDV $this->getDoctrine()
  5239.                     ->getRepository(ClientTemp::class)
  5240.                     ->findOneBy(['id' => $rdv->getIdClientTemp()->getId()]);
  5241.                 $clientRDV->setName($data["prenom_patient"]);
  5242.                 $clientRDV->setLastname($data["nom_patient"]);
  5243.                 $clientRDV->setBirthdate($birth);
  5244.                 $clientRDV->setMail($data["mail_patient"]);
  5245.                 $clientRDV->setPhone($data["portable_patient"]);
  5246.                 $clientRDV->setPhoneFixe($data["fixe_patient"]);
  5247.             }
  5248.             $entityManager->flush();
  5249.         }
  5250.         if (is_null($rdv->getIdClient())) {
  5251.             $prenom_patient $rdv->getIdClientTemp()->getName();
  5252.             $nom_patient $rdv->getIdClientTemp()->getLastname();
  5253.             $mail_patient $rdv->getIdClientTemp()->getMail();
  5254.             $portable_patient $rdv->getIdClientTemp()->getPhone();
  5255.             $fixe_patient $rdv->getIdClientTemp()->getPhoneFixe();
  5256.             $birthday $rdv->getIdClientTemp()->getBirthdate();
  5257.         } elseif (is_null($rdv->getIdClientTemp())) {
  5258.             $prenom_patient =  $rdv->getIdClient()->getName();
  5259.             $nom_patient $rdv->getIdClient()->getLastname();
  5260.             $mail_patient $rdv->getIdClient()->getMail();
  5261.             $portable_patient $rdv->getIdClient()->getPhone();
  5262.             $fixe_patient $rdv->getIdClient()->getPhoneFixe();
  5263.             $birthday $rdv->getIdClient()->getBirthdate();
  5264.         } else {
  5265.             $prenom_patient "";
  5266.             $nom_patient "";
  5267.             $mail_patient "";
  5268.             $portable_patient "";
  5269.             $fixe_patient "";
  5270.             $birthday "";
  5271.         }
  5272.         return new Response(json_encode(([
  5273.             "id" => $rdv->getId(),
  5274.             "motif_id" => $rdv->getIdMotif()->getId(),
  5275.             "motif_libelle" => $rdv->getIdMotif()->getTitre(),
  5276.             "audio_id" => $rdv->getIdAudio()->getId(),
  5277.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  5278.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  5279.             "fullName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  5280.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  5281.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  5282.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  5283.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  5284.             "centre_name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : null,
  5285.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  5286.             "etat_id" => $rdv->getIdEtat()->getId(),
  5287.             "date" => $rdv->getDate(),
  5288.             "comment" => $rdv->getComment(),
  5289.             "note" => $rdv->getNote(),
  5290.             "review" => $rdv->getReview(),
  5291.             "prenom_patient" => $prenom_patient,
  5292.             "nom_patient" => $nom_patient,
  5293.             "mail_patient" => $mail_patient,
  5294.             "portable_patient" => $portable_patient,
  5295.             "fixe_patient" => $fixe_patient,
  5296.             "birthday" => $birthday,
  5297.             "status" => 200,
  5298.         ])));
  5299.     }
  5300.     /**
  5301.      * @Route("/rdv/{id}/supp", name="suppRdvByID", methods={"PUT"})
  5302.      */
  5303.     public function suppRdvByID(PublicFunction $publicFunctionRdv $rdvRequest $requestGoogleCalendarService $googleCalendarRdvSmsService $rdvSms): Response
  5304.     {
  5305.         $pastDate $rdv->getDate();
  5306.         $data json_decode($request->getContent(), true);
  5307.         $entityManager $this->getDoctrine()->getManager();
  5308.         if (!isset($data["token"])) {
  5309.             return new Response(json_encode([
  5310.                 "message" => "Pas de token n'a été spécifié",
  5311.                 "status" => 401,
  5312.             ]), 401);
  5313.         }
  5314.         /** @var Token */
  5315.         $token $this->getDoctrine()
  5316.             ->getRepository(Token::class)
  5317.             ->findOneBy(['token' => $data["token"]]);
  5318.         if (!$token) {
  5319.             return new Response(json_encode([
  5320.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  5321.                 "status" => 404,
  5322.             ]), 404);
  5323.         }
  5324.         // get token age
  5325.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  5326.         // if the token if older than 7 days
  5327.         if ($dateDiff->7) {
  5328.             $entityManager->remove($token);
  5329.             $entityManager->flush();
  5330.             return $this->json([
  5331.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  5332.                 'path' => 'src/Controller/ClientController.php',
  5333.                 "status" => 401,
  5334.             ], 401);
  5335.         }
  5336.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  5337.             return new Response(json_encode([
  5338.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  5339.                 "status" => 404,
  5340.             ]), 404);
  5341.         }
  5342.         // delete google agenda event
  5343.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  5344.             ->findBy(array('rdv' => $rdv));
  5345.         //dd($rdvEvents);
  5346.         $synchronisationCosium $this->getDoctrine()->getRepository(SynchronisationCosium::class)->findOneBy(["audio" => $rdv->getIdAudio()->getId()]);
  5347.         $cosiumCenter $this->getDoctrine()->getRepository(CosiumCenter::class)->findBy(["synchronisationCosium" => $synchronisationCosium"center" => $rdv->getIdCentre()]);
  5348.         if ($cosiumCenter) {
  5349.             $this->clientCosiumService->deleteRdv($synchronisationCosium$rdv);
  5350.         }
  5351.         foreach ($rdvEvents as $rdvEvent) {
  5352.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  5353.             $googleCalendar->deleteEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId());
  5354.             $entityManager->remove($rdvEvent);
  5355.             $entityManager->flush();
  5356.         }
  5357.         $etat $this->getDoctrine()
  5358.             ->getRepository(EtatRdv::class)
  5359.             ->findOneBy(['id' => 2]);
  5360.         if ($etat == null) {
  5361.             return new Response(json_encode(([
  5362.                 'message' => 'Error, no etat found at this id',
  5363.                 'path' => 'src/Controller/TrustedUserController.php',
  5364.                 "status" => 400,
  5365.             ])), 400);
  5366.         }
  5367.         $rdv->setIdEtat($etat);
  5368.         $rdv->setCacher(1);
  5369.         ////// SMSEMAIL A décommenter pour activer l'envoi de SMS + MAIL pour modification annulation de RDV, coté audio / client SMSEMAIL ////
  5370.         $date $rdv->getDate();
  5371.         $smsDate $date->format('d-m-Y H:i');
  5372.         $oldDate $pastDate->format('d-m-Y H:i');
  5373.         $locale 'fr_FR';
  5374.         $formatter = new IntlDateFormatter(
  5375.             $locale,
  5376.             IntlDateFormatter::FULL,
  5377.             IntlDateFormatter::SHORT,
  5378.             null,
  5379.             IntlDateFormatter::GREGORIAN,
  5380.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  5381.         );
  5382.         $smsDateLongFormat $formatter->format($date);
  5383.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  5384.         $frenchDate ucfirst($frenchDate);
  5385.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  5386.         // notif client
  5387.         if ($rdv->getIdEtat()->getId() != 2) {
  5388.             $params = array(
  5389.                 "lienModifier" => "{$_ENV['BASE_client']}mes-rendez-vous",
  5390.                 "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  5391.                 "date" => $smsDateLongFormat,
  5392.                 "heure" => substr($smsDate1115),
  5393.                 "motif" => $rdv->getIdMotif()->getTitre(),
  5394.                 "centerName" => $rdv->getIdCentre()->getName(),
  5395.                 "centerAddress" => $rdv->getIdCentre()->getAddress(),
  5396.                 "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  5397.                 "audioMail" => $rdv->getIdAudio()->getMail(),
  5398.                 "centerPhone" => $rdv->getIdCentre()->getPhone(),
  5399.                 "centerCity" => $rdv->getIdCentre()->getCity(),
  5400.                 "clientEmail" => $client->getMail(),
  5401.                 "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  5402.                 'titre' => 'Votre rendez-vous est modifié pour le',
  5403.                 'frenchDate' => $frenchDate
  5404.             );
  5405.             $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  5406.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject205);
  5407.             $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.";
  5408.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  5409.             // creer un mail de notif pour myAudio + créé le template LP | MA | RR - Modification du RDV - Centre Auditif - MyAudio
  5410.             $subjectMyaudio "Rendez-vous My Audio a été modifié par l'audioprothésiste " $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName();
  5411.             $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$client->getName() . ' ' $client->getLastName(), $subjectMyaudio206);
  5412.         }
  5413.         //     //// == suppression
  5414.         else if ($rdv->getIdEtat()->getId() == 2) {
  5415.             $params = array(
  5416.                 "date" => substr($smsDate010),
  5417.                 "lien" => "{$_ENV['BASE_client']}search",
  5418.                 "heure" => substr($smsDate1115),
  5419.                 "patientName" => $client->getLastName() . ' ' $client->getName(),
  5420.                 'titre' => 'Votre rendez-vous est annulé :',
  5421.                 'centerName' => $rdv->getIdCentre()->getName(),
  5422.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  5423.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  5424.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  5425.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  5426.                 "clientEmail" => $client->getMail() ?? '',
  5427.                 "clientPhone" => $client->getPhone() ?? '',
  5428.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  5429.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  5430.                 'motif' => $rdv->getIdMotif()->getTitre(),
  5431.             );
  5432.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  5433.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject188);
  5434.             $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  5435.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  5436.             // creer un mail de notif pour myAudio + créé le template LP | MA | RR - Annlation du RDV - Centre Auditif - MyAudio
  5437.             $subjectMyaudio $rdv->getIdCentre()->getName() . " a annulé un rendez-vous My Audio avec " $client->getName() . ' ' $client->getLastName();
  5438.             $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$client->getName() . ' ' $client->getLastName(), $subjectMyaudio207);
  5439.         }
  5440.         //notif Audio
  5441.         if ($rdv->getIdEtat()->getId() != 2) {
  5442.             $params = array(
  5443.                 "lienModifier" => "{$_ENV['BASE_logiciel']}rdv",
  5444.                 "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  5445.                 "date" => substr($smsDate010),
  5446.                 "frenchDate" => $frenchDate,
  5447.                 "heure" => substr($smsDate1115),
  5448.                 'motif' => $rdv->getIdMotif()->getTitre(),
  5449.                 'clientPhone' => $client->getPhone(),
  5450.                 'clientNom' => $client->getLastname(),
  5451.                 'clientPrenom' => $client->getName(),
  5452.                 'clientCivilite' => $client->getCivilite(),
  5453.                 'clientPostal' => $client->getPostal(),
  5454.                 'clientMail' => $client->getMail(),
  5455.                 'centerName' => $rdv->getIdCentre()->getName(),
  5456.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  5457.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  5458.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  5459.                 'idPatient' => $client->getId(),
  5460.                 'proUrl' => "{$_ENV['BASE_logiciel']}",
  5461.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  5462.                 'titre' => 'Votre rendez-vous est modifié pour le :'
  5463.             );
  5464.             $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  5465.             $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  5466.             if ($rdv->getIdAudio()->getModifRdvMail()) {
  5467.                 $subject "🔀 Rendez-vous My Audio modifié du " $frenchDate " à " substr($smsDate1115);
  5468.                 $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject186);
  5469.             }
  5470.             if ($rdv->getIdAudio()->getModifRdvSms()) {
  5471.                 $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.";
  5472.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  5473.             }
  5474.         } else if ($rdv->getIdEtat()->getId() == 2) {
  5475.             /* $params = array(  
  5476.                     "date" => substr($smsDate, 0, 10),
  5477.                     "lien"=> "{$_ENV['BASE_client']}search",
  5478.                     "heure" =>substr($smsDate, 11, 15),
  5479.                     "patientName" => $client->getLastName(),
  5480.                     'titre' => 'Votre rendez-vous est annulé :',
  5481.                     'centerName' => $rdv->getIdCentre()->getName(),
  5482.                     'centerPostal' => $rdv->getIdCentre()->getPostale(),
  5483.                     'centerCity' => $rdv->getIdCentre()->getCity(),
  5484.                     'centerAddress' => $rdv->getIdCentre()->getAddress(),
  5485.                     'centerPhone' => $rdv->getIdCentre()->getPhone(),
  5486.                     'audioproName' => $rdv->getIdAudio()->getCivilite().' '. $rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(),                    
  5487.                     'audioMail' => $rdv->getIdAudio()->getMail(),
  5488.                     'motif' => $rdv->getIdMotif()->getTitre(),
  5489.                 );
  5490.                 $subject = "Rendez-vous My Audio annulé avec " . $rdv->getIdCentre()->getName();
  5491.                 $publicFunction->sendEmail($params, $rdv->getIdAudio()->getMail(), $rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(), $subject, 188 );
  5492.                 $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.";
  5493.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $rdv->getIdAudio()->getPhone());
  5494.                 */
  5495.         }
  5496.         // delete sms notification     
  5497.         $rdvSms->deleteAssociatedRdvSms($rdv);
  5498.         // delete client device
  5499.         /*$clientDevice = $this->getDoctrine()->getRepository(ClientDevice::class)->findOneBy(['rdv' => $rdv]);
  5500. if($clientDevice)
  5501. {
  5502. if ($client instanceof Client) {
  5503.     $nextRdvs = $this->getDoctrine()
  5504.         ->getRepository(Rdv::class)
  5505.         ->findBy([
  5506.             "id_client" => $rdv->getIdClient(),
  5507.             "id_motif" => ['106', '107', '108', '109'] 
  5508.         ]);
  5509.         $client->setClientStatus(null);
  5510. } elseif ($client instanceof ClientTemp) {
  5511.  $nextRdvs = $this->getDoctrine()
  5512.         ->getRepository(Rdv::class)
  5513.         ->findBy([
  5514.             "id_client_temp" => $rdv->getIdClientTemp(),
  5515.             "id_motif" => ['106', '107', '108', '109'] 
  5516.         ]);
  5517.         $client->setClientStatus(null);
  5518.     } 
  5519.     $locale = 'fr_FR';
  5520.     $fmt = new IntlDateFormatter($locale, IntlDateFormatter::FULL, IntlDateFormatter::NONE);
  5521.     $fmt->setPattern("EEEE dd MMMM yyyy"); 
  5522.     if($nextRdvs){
  5523.     $params = array(  
  5524.                 "title" => "Affectation de votre appareil et programmation de vos rendez-vous",
  5525.                 "centerName" => "{$rdv->getIdCentre()->getName()}",
  5526.                 "audioName" => "{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastName()}",
  5527.                 "centerAddress" => "{$rdv->getIdCentre()->getAddress()}",
  5528.                 "device" => "{$clientDevice->getDevice()->getModel()}",
  5529.                 "ears" => "{$clientDevice->getSettingDevice()->getName()}",
  5530.                 "rdvOneDate" => "{$fmt->format($nextRdvs['0']->getDate())}",
  5531.                 "rdvOneHour" => "{$nextRdvs['0']->getDate()->format('H:i')}",
  5532.                 "rdvTwoDate" => "{$fmt->format($nextRdvs['1']->getDate())}",
  5533.                 "rdvTwoHour" => "{$nextRdvs['1']->getDate()->format('H:i')}",
  5534.                 "rdvThreeDate" => "{$fmt->format($nextRdvs['2']->getDate())}",
  5535.                 "rdvThreeHour" => "{$nextRdvs['2']->getDate()->format('H:i')}",
  5536.                 "rdvFourDate" => "{$fmt->format($nextRdvs['3']->getDate())}",
  5537.                 "rdvFourHour" => "{$nextRdvs['3']->getDate()->format('H:i')}",
  5538.             );
  5539.     
  5540.             $publicFunction->sendEmail($params, $client->getMail(), $client->getName().' '.$client->getLastName(), "Annulation de vos prochains RDV", 162 );
  5541.         }
  5542.     foreach($nextRdvs as $rdv)
  5543.     {
  5544.         $entityManager->remove($rdv);
  5545.     }
  5546.     $entityManager->persist($client);
  5547.     $entityManager->remove($clientDevice);
  5548.     $entityManager->flush();
  5549. }*/
  5550.         // Before deleting, publish the deletion event
  5551.         $this->mercure->publishRdvDeletion($rdv);
  5552.         $entityManager->flush();
  5553.         return new Response(json_encode(([
  5554.             "id" => $rdv->getId(),
  5555.             "motif_id" => $rdv->getIdMotif()->getId(),
  5556.             "motif_libelle" => $rdv->getIdMotif()->getTitre(),
  5557.             "audio_id" => $rdv->getIdAudio()->getId(),
  5558.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  5559.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  5560.             "fullName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  5561.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  5562.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  5563.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  5564.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  5565.             "centre_name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : null,
  5566.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  5567.             "etat_id" => $rdv->getIdEtat()->getId(),
  5568.             "date" => $rdv->getDate(),
  5569.             "comment" => $rdv->getComment(),
  5570.             "note" => $rdv->getNote(),
  5571.             "review" => $rdv->getReview(),
  5572.             "status" => 200,
  5573.         ])));
  5574.     }
  5575.     /**
  5576.      * @Route("/rdv/calendar", name="postRdvCalendar", methods={"POST"})
  5577.      */
  5578.     public function postRdvCalendar(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendarRdvSmsService $rdvSmsPublisherInterface $publisher): Response
  5579.     {
  5580.         $data json_decode($request->getContent(), true);
  5581.         if (!isset($data["token"])) {
  5582.             return new Response(json_encode([
  5583.                 "message" => "Pas de token n'a été spécifié",
  5584.                 "status" => 401,
  5585.             ]), 401);
  5586.         }
  5587.         $entityManager $this->getDoctrine()->getManager();
  5588.         /** @var Token */
  5589.         $token $this->getDoctrine()
  5590.             ->getRepository(Token::class)
  5591.             ->findOneBy(['token' => $data["token"]]);
  5592.         if (!$token) {
  5593.             return new Response(json_encode([
  5594.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  5595.                 "status" => 404,
  5596.             ]), 404);
  5597.         }
  5598.         // get token age
  5599.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  5600.         // if the token if older than 7 days
  5601.         if ($dateDiff->7) {
  5602.             $entityManager->remove($token);
  5603.             $entityManager->flush();
  5604.             return $this->json([
  5605.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  5606.                 'path' => 'src/Controller/ClientController.php',
  5607.                 "status" => 401,
  5608.             ], 401);
  5609.         }
  5610.         // makes the rdv
  5611.         $rdv = new Rdv();
  5612.         if ($token->getIdAudio()) {
  5613.             //if the token if for an audio
  5614.             $audio $token->getIdAudio();
  5615.             if ((isset($data["client_id"]))) {
  5616.                 $client $this->getDoctrine()
  5617.                     ->getRepository(Client::class)
  5618.                     ->findOneBy(['id' => $data["client_id"]]);
  5619.             } else {
  5620.                 $client $this->getDoctrine()
  5621.                     ->getRepository(ClientTemp::class)
  5622.                     ->findOneBy(['id' => $data["client_id_temp"]]);
  5623.             }
  5624.             if ($client == null) {
  5625.                 return new Response(json_encode(([
  5626.                     'message' => 'Error, no client found at this id',
  5627.                     'path' => 'src/Controller/RdvController.php',
  5628.                     "status" => 400,
  5629.                 ])), 400);
  5630.             }
  5631.         } elseif ($token->getIdClient()) {
  5632.             //if the token if for a client
  5633.             $client $token->getIdClient();
  5634.             /** @var Audio */
  5635.             $audio $this->getDoctrine()
  5636.                 ->getRepository(Audio::class)
  5637.                 ->findOneBy(['id' => $data["audio_id"]]);
  5638.             if (isset($data["proche_id"])) {
  5639.                 $proche $this->getDoctrine()
  5640.                     ->getRepository(Proches::class)
  5641.                     ->findOneBy(['id' => $data["proche_id"], "id_client" => $client]);
  5642.             }
  5643.             if ($audio == null) {
  5644.                 return new Response(json_encode(([
  5645.                     'message' => 'Error, no audio found at this id',
  5646.                     'path' => 'src/Controller/RdvController.php',
  5647.                     "status" => 400,
  5648.                 ])), 400);
  5649.             }
  5650.         } else {
  5651.             return new Response(json_encode(([
  5652.                 'message' => 'Error, token is not an audio token',
  5653.                 'path' => 'src/Controller/RdvController.php',
  5654.                 "status" => 400,
  5655.             ])), 400);
  5656.         }
  5657.         $rdv->setIdAudio($audio);
  5658.         if (isset($proche)) {
  5659.             $rdv->setIdProche($proche);
  5660.         }
  5661.         if (isset($data["client_id_temp"])) {
  5662.             $rdv->setIdClientTemp($client);
  5663.         } else {
  5664.             $rdv->setIdClient($client);
  5665.         }
  5666.         $rdv->setCacher(0);
  5667.         /** @var Centre */
  5668.         if (isset($data["centre_id"])) {
  5669.             $centre $this->getDoctrine()
  5670.                 ->getRepository(Centre::class)
  5671.                 ->findOneBy(['id' => $data["centre_id"]]);
  5672.             if ($centre == null) {
  5673.                 return new Response(json_encode(([
  5674.                     'message' => 'Error, no centre found at this id',
  5675.                     'path' => 'src/Controller/RdvController.php',
  5676.                     "status" => 400,
  5677.                 ])), 400);
  5678.             }
  5679.             /** @var AudioCentre */
  5680.             $liaison $this->getDoctrine()
  5681.                 ->getRepository(AudioCentre::class)
  5682.                 ->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
  5683.             if ($liaison == null) {
  5684.                 return new Response(json_encode(([
  5685.                     'message' => 'Error, audio isnt part of the centre',
  5686.                     'path' => 'src/Controller/RdvController.php',
  5687.                     "status" => 400,
  5688.                 ])), 400);
  5689.             }
  5690.             $rdv->setIdCentre($centre);
  5691.         } elseif (isset($data["lieu_id"]) && $audio->getIsIndie()) {
  5692.             // tries to set the lieu if it's an audio indie
  5693.             $lieu $this->getDoctrine()
  5694.                 ->getRepository(Lieu::class)
  5695.                 ->findOneBy(['id' => $data["lieu_id"], 'id_gerant' => $data["audio_id"]]);
  5696.             if ($lieu == null) {
  5697.                 return new Response(json_encode(([
  5698.                     'message' => 'Error, no lieu found at this id',
  5699.                     'path' => 'src/Controller/RdvController.php',
  5700.                     "status" => 400,
  5701.                 ])), 400);
  5702.             }
  5703.             $rdv->setIdLieu($lieu);
  5704.         } else {
  5705.             return new Response(json_encode(([
  5706.                 'message' => 'Error, no lieu/centre id',
  5707.                 'path' => 'src/Controller/RdvController.php',
  5708.                 "status" => 400,
  5709.             ])), 400);
  5710.         }
  5711.         /** @var Motif */
  5712.         $motif $this->getDoctrine()
  5713.             ->getRepository(Motif::class)
  5714.             ->find($data["motif_id"]);
  5715.         if ($motif == null) {
  5716.             return new Response(json_encode(([
  5717.                 'message' => 'Error, no motif found at this id',
  5718.                 'path' => 'src/Controller/RdvController.php',
  5719.                 "status" => 400,
  5720.             ])), 400);
  5721.         }
  5722.         /** @var AudioMotif */
  5723.         $audioMotif $this->getDoctrine()
  5724.             ->getRepository(AudioMotif::class)
  5725.             ->findOneBy(["id_audio" => $audio->getId(), "id_motif" => $data["motif_id"]]);
  5726.         if ($audioMotif == null) {
  5727.             return new Response(json_encode(([
  5728.                 'message' => 'Error, no motif of this id found at this audio',
  5729.                 'path' => 'src/Controller/RdvController.php',
  5730.                 "status" => 400,
  5731.             ])), 400);
  5732.         }
  5733.         // remove the taken schedule by rdv to make sure there is no overlap
  5734.         $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  5735.         if (isset($data["note"])) {
  5736.             $rdv->setNote($data["note"]);
  5737.         }
  5738.         // test if the audio is available
  5739.         /*   if (isset($data["lieu_id"]) && $audio->getIsIndie()){
  5740.             if ($publicFunction->calculScheduleFitDate($audio, $date, $audioMotif->getDuration(), null, $lieu) == false) {
  5741.                 return new Response(json_encode(([
  5742.                     'message' => 'Error, no timestamp found at this time',
  5743.                     'path' => 'src/Controller/RdvController.php',
  5744.                     "status" => 400,
  5745.                 ])), 400);
  5746.             }
  5747.         } else {
  5748.             if ($publicFunction->calculScheduleFitDate($audio, $date, $audioMotif->getDuration(), $centre , null) == true) {
  5749.                 return new Response(json_encode(([
  5750.                     'message' => 'Error, no timestamp found at this time',
  5751.                     'path' => 'src/Controller/RdvController.php',
  5752.                     "status" => 400,
  5753.                 ])), 400);
  5754.             }
  5755.         }*/
  5756.         $rdv->setDate($date);
  5757.         $rdv->setDateCreation(\DateTime::createFromFormat("d/m/Y H:i"date('d/m/Y H:i')));
  5758.         /** @var EtatRdv */
  5759.         $etat $this->getDoctrine()
  5760.             ->getRepository(EtatRdv::class)
  5761.             ->findOneBy(['id' => $data["etat_id"]]);
  5762.         if ($etat == null) {
  5763.             return new Response(json_encode(([
  5764.                 'message' => 'Error, no etat found at this id',
  5765.                 'path' => 'src/Controller/RdvController.php',
  5766.                 "status" => 400,
  5767.             ])), 400);
  5768.         }
  5769.         $rdv->setIdEtat($etat);
  5770.         $rdv->setIdMotif($motif);
  5771.         $rdv->setDuration($data["duree"]);
  5772.         $rdv->setIsAbsence($data["is_absence"]);
  5773.         $entityManager $this->getDoctrine()->getManager();
  5774.         $entityManager->persist($rdv);
  5775.         $entityManager->flush();
  5776.         $date $rdv->getDate();
  5777.         $smsDate $date->format('d-m-Y H:i');
  5778.         $locale 'fr_FR';
  5779.         $formatter = new IntlDateFormatter(
  5780.             $locale,
  5781.             IntlDateFormatter::FULL,
  5782.             IntlDateFormatter::SHORT,
  5783.             null,
  5784.             IntlDateFormatter::GREGORIAN,
  5785.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  5786.         );
  5787.         $smsDateLongFormat $formatter->format($date);
  5788.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  5789.         // client notif mail Sms
  5790.         // we send parametre for the trait methid
  5791.         //$params = $this->emailNotificationService->prepareEmailParams($user);
  5792.         // send email notifcation
  5793.         //$this->emailNotificationService->sendEmail($params, 'admin@example.com', 'Nouvelle inscription à My Audio Pro', 1);
  5794.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  5795.         $frenchDate ucfirst($frenchDate);
  5796.         $params = array(
  5797.             "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  5798.             "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  5799.             "date" => $smsDateLongFormat,
  5800.             "prenom" => $client->getName(),
  5801.             //"heure" => $smsDatee,
  5802.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  5803.             "centerName" => $rdv->getIdCentre()->getName(),
  5804.             "centerAddress" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  5805.             "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  5806.             "centerCity" => $rdv->getIdCentre()->getCity(),
  5807.             "motif" => $rdv->getIdMotif()->getTitre(),
  5808.             "RdvDate" => substr($smsDate010) . " à "  substr($smsDate1115),
  5809.             "audioName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  5810.             "clientMail" => $client->getMail(),
  5811.             "clientPhone" => $client->getPhone(),
  5812.             'titre' => "Votre rendez-vous est validé le " substr($smsDate010) . " à "  substr($smsDate1115),
  5813.             "address" => $rdv->getIdCentre()->getAddress(),
  5814.             "postal" => $rdv->getIdCentre()->getPostale(),
  5815.             "city" => $rdv->getIdCentre()->getCity(),
  5816.             "clientEmail" => $client->getMail(),
  5817.             "clientPassword" => isset($data["passwordGenerated"]) ? $data["passwordGenerated"] : null,
  5818.             "clientAddress" => $client->getAddress(),
  5819.             "clientPostal" => $client->getPostal(),
  5820.             "clientCity" => $client->getCity(),
  5821.             "audioName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  5822.             "frenchDate" => $frenchDate,
  5823.             "heure" => substr($smsDate1115),
  5824.             "centerName" => $rdv->getIdCentre()->getName(),
  5825.             "audioMail" => $rdv->getIdAudio()->getMail(),
  5826.             "modifUrl" => "{$_ENV['BASE_client']}mes-rendez-vous",
  5827.         );
  5828.         $subject "Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  5829.         $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject181);
  5830.         $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.";
  5831.         // $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $client->getPhone());
  5832.         // audio Notif mail SMS
  5833.         /* $params = array(  
  5834.                         "lienModifer" =>"{$_ENV['BASE_logiciel']}rdv",
  5835.                         "lienAnnule"=> "{$_ENV['BASE_logiciel']}rdv",
  5836.                         "date" => substr($smsDate, 0, 10),
  5837.                         "heure" =>substr($smsDate, 11, 15),
  5838.                         'motif' => $rdv->getIdMotif()->getTitre(),
  5839.                         'clientPhone'=> $client->getPhone(),
  5840.                         'clientNom' =>$client->getLastname(),
  5841.                         'clientPrenom' =>$client->getName(),
  5842.                         'clientCivilite' => $client->getCivilite(),
  5843.                         'clientPostal' => $client->getPostal(),
  5844.                         'clientMail' => $client->getMail(),
  5845.                         'centerName' => $rdv->getIdCentre()->getName(),
  5846.                         'centerPostal' => $rdv->getIdCentre()->getPostale(),
  5847.                         'centerCity' => $rdv->getIdCentre()->getCity(),
  5848.                         'centerAddress' => $rdv->getIdCentre()->getAddress(),
  5849.                         'idPatient' => $client->getId(),
  5850.                         'proUrl' => "{$_ENV['BASE_logiciel']}",
  5851.                         'audioproName' => $rdv->getIdAudio()->getCivilite().' '.$rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(),
  5852.                         'titre' => 'Votre rendez-vous est modifié pour le :'
  5853.                     );
  5854.         $subject = "🔀 Rendez-vous My Audio modifié du ". $frenchDate . " à " . substr($smsDate, 11, 15);
  5855.         $publicFunction->sendEmail($params, $rdv->getIdAudio()->getMail(), $rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(), $subject, 186 );
  5856.         $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.";
  5857.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $rdv->getIdAudio()->getPhone());*/
  5858.         // google calendar post
  5859.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  5860.             ->findBy(array('audio' => $audio->getId()));
  5861.         $data['rdv'] = $rdv->getId();
  5862.         $synchronisationCosium $this->getDoctrine()->getRepository(SynchronisationCosium::class)->findOneBy(["audio" => $audio->getId()]);
  5863.         $cosiumCenter $this->getDoctrine()->getRepository(CosiumCenter::class)->findOneBy(["synchronisationCosium" => $synchronisationCosium"center" => $rdv->getIdCentre()]);
  5864.         if ($cosiumCenter) {
  5865.             $this->clientCosiumService->createAgenda($synchronisationCosium$rdv$cosiumCenter);
  5866.         }
  5867.         foreach ($synchronisations as $synchronisation) {
  5868.             if (!$synchronisation->getIsDeleted()) {
  5869.                 try {
  5870.                     $googleCalendar->checkAndRefreshAccessToken($synchronisation);
  5871.                     $googleCalendar->createEvent($synchronisation$data);
  5872.                 } catch (\Exception $e) {
  5873.                     error_log('Error refreshing access token or creating event: ' $e->getMessage());
  5874.                 }
  5875.             }
  5876.         }
  5877.         // create schedule notification sms
  5878.         $rdvSms->storeRdvSmsNotifications($rdv);
  5879.         if ($rdv->getClientDevice()) {
  5880.             $nextRdv $this->getDoctrine()
  5881.                 ->getRepository(Rdv::class)
  5882.                 ->find($rdv->getClientDevice()->getRdv()->getId());
  5883.             if ($nextRdv->getIdClientTemp()) {
  5884.                 $nextRdvs $this->getDoctrine()
  5885.                     ->getRepository(Rdv::class)
  5886.                     ->findBy([
  5887.                         "id_client_temp" => $nextRdv->getIdClientTemp(),
  5888.                         "id_motif" => ['106''107''108''109']
  5889.                     ]);
  5890.             } else {
  5891.                 $nextRdvs $this->getDoctrine()
  5892.                     ->getRepository(Rdv::class)
  5893.                     ->findBy([
  5894.                         "id_client" => $nextRdv->getIdClient(),
  5895.                         "id_motif" => ['106''107''108''109']
  5896.                     ]);
  5897.             }
  5898.             $mappedNextRdvs array_map(function ($rdv) {
  5899.                 return [
  5900.                     'id' => $rdv->getId(),
  5901.                     'date' => $rdv->getDate()->format('d-m-Y'),
  5902.                     'hours' => $rdv->getDate()->format('H:i'),
  5903.                     'duration' => $rdv->getDuration(),
  5904.                     "motif_id" => $rdv->getIdMotif()->getId(),
  5905.                     "motif_titre" => $rdv->getIdMotif()->getTitre(),
  5906.                     "duration" => $rdv->getDuration(),
  5907.                 ];
  5908.             }, $nextRdvs);
  5909.         }
  5910. $token $this->entityManager
  5911.      ->getRepository(Token::class)
  5912.      ->findOneBy(['token' => $data['token']]);
  5913. $tokenAudioId $token->getIdAudio()->getId();
  5914. $requestAudioId $data['audio_id'] ?? null;
  5915. $requestCenterId $data['center_id'] ?? null;
  5916. // Check audio
  5917. if ($requestAudioId && $requestAudioId == $tokenAudioId) {
  5918.     // Verify center belongs to this audio
  5919.     $centre $this->entityManager
  5920.         ->getRepository(Centre::class)
  5921.         ->findOneBy(['id_gerant' => $tokenAudioId]);
  5922.     if ($centre && $centre->getId() == $requestCenterId) {
  5923.         // All conditions ok → send mercure update
  5924.         $this->mercure->publishRdvUpdate($rdv'created');
  5925.     }
  5926. }
  5927.         return new Response(json_encode(([
  5928.             "id" => $rdv->getId(),
  5929.             "motif_id" => $rdv->getIdMotif()->getId(),
  5930.             "audio_id" => $rdv->getIdAudio()->getId(),
  5931.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  5932.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  5933.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  5934.             "centerName" => $rdv->getIdCentre()->getName(),
  5935.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  5936.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  5937.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  5938.             "duration" => $data["duree"],
  5939.             "etat_id" => $rdv->getIdEtat()->getId(),
  5940.             "date" => $rdv->getDate(),
  5941.             "clientEtatId" => $client->getClientStatus() ? $client->getClientStatus()->getId() : 0,
  5942.             "isClient" => ($client instanceof Client) ? 0,
  5943.             "device" => $rdv->getClientDevice() ? [
  5944.                 "isDevice" => true,
  5945.                 "deviceID" => $rdv->getClientDevice()->getDevice()->getId(),
  5946.                 "clientDeviceID" => $rdv->getClientDevice()->getId(),
  5947.                 "deviceModel" => $rdv->getClientDevice()->getDevice()->getModel(),
  5948.                 "settingName" => $rdv->getClientDevice()->getSettingDevice()->getName(),
  5949.                 "settingDeviceId" => $rdv->getClientDevice()->getSettingDevice()->getSlug(),
  5950.                 "settingSlug" => $rdv->getClientDevice()->getSettingDevice()->getSlug(),
  5951.                 "nextRdvs" => $mappedNextRdvs
  5952.             ] : [
  5953.                 "isDevice" => false
  5954.             ],
  5955.             "comment" => $rdv->getComment(),
  5956.             "review" => $rdv->getReview(),
  5957.             "note" => $rdv->getNote(),
  5958.             "status" => 200,
  5959.         ])));
  5960.     }
  5961.     /**
  5962.      * @Route("/rdv/absence", name="postAbsenceCalendar", methods={"POST"})
  5963.      */
  5964.     public function postAbsenceCalendar(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendar): Response
  5965.     {
  5966.         $data json_decode($request->getContent(), true);
  5967.         if (!isset($data["token"])) {
  5968.             return new Response(json_encode([
  5969.                 "message" => "Pas de token n'a été spécifié",
  5970.                 "status" => 401,
  5971.             ]), 401);
  5972.         }
  5973.         $entityManager $this->getDoctrine()->getManager();
  5974.         /** @var Token */
  5975.         $token $this->getDoctrine()
  5976.             ->getRepository(Token::class)
  5977.             ->findOneBy(['token' => $data["token"]]);
  5978.         if (!$token) {
  5979.             return new Response(json_encode([
  5980.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  5981.                 "status" => 404,
  5982.             ]), 404);
  5983.         }
  5984.         // get token age
  5985.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  5986.         // if the token if older than 7 days
  5987.         if ($dateDiff->7) {
  5988.             $entityManager->remove($token);
  5989.             $entityManager->flush();
  5990.             return $this->json([
  5991.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  5992.                 'path' => 'src/Controller/ClientController.php',
  5993.                 "status" => 401,
  5994.             ], 401);
  5995.         }
  5996.         // makes the rdv
  5997.         $rdv = new Rdv();
  5998.         $audio $token->getIdAudio();
  5999.         $rdv->setIdAudio($audio);
  6000.         /** @var Centre */
  6001.         if (isset($data["centre_id"])) {
  6002.             $centre $this->getDoctrine()
  6003.                 ->getRepository(Centre::class)
  6004.                 ->findOneBy(['id' => $data["centre_id"]]);
  6005.             if ($centre == null) {
  6006.                 return new Response(json_encode(([
  6007.                     'message' => 'Error, no centre found at this id',
  6008.                     'path' => 'src/Controller/RdvController.php',
  6009.                     "status" => 400,
  6010.                 ])), 400);
  6011.             }
  6012.             /** @var AudioCentre */
  6013.             $liaison $this->getDoctrine()
  6014.                 ->getRepository(AudioCentre::class)
  6015.                 ->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
  6016.             if ($liaison == null) {
  6017.                 return new Response(json_encode(([
  6018.                     'message' => 'Error, audio isnt part of the centre',
  6019.                     'path' => 'src/Controller/RdvController.php',
  6020.                     "status" => 400,
  6021.                 ])), 400);
  6022.             }
  6023.             $rdv->setIdCentre($centre);
  6024.         } elseif (isset($data["lieu_id"]) && $audio->getIsIndie()) {
  6025.             // tries to set the lieu if it's an audio indie
  6026.             $lieu $this->getDoctrine()
  6027.                 ->getRepository(Lieu::class)
  6028.                 ->findOneBy(['id' => $data["lieu_id"], 'id_gerant' => $data["audio_id"]]);
  6029.             if ($lieu == null) {
  6030.                 return new Response(json_encode(([
  6031.                     'message' => 'Error, no lieu found at this id',
  6032.                     'path' => 'src/Controller/RdvController.php',
  6033.                     "status" => 400,
  6034.                 ])), 400);
  6035.             }
  6036.             $rdv->setIdLieu($lieu);
  6037.         } else {
  6038.             return new Response(json_encode(([
  6039.                 'message' => 'Error, no lieu/centre id',
  6040.                 'path' => 'src/Controller/RdvController.php',
  6041.                 "status" => 400,
  6042.             ])), 400);
  6043.         }
  6044.         // remove the taken schedule by rdv to make sure there is no overlap
  6045.         $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  6046.         $rdv->setDate($date);
  6047.         $rdv->setDateCreation(\DateTime::createFromFormat("d/m/Y H:i"date('d/m/Y H:i')));
  6048.         /** @var EtatRdv */
  6049.         $etat $this->getDoctrine()
  6050.             ->getRepository(EtatRdv::class)
  6051.             ->findOneBy(['id' => $data["etat_id"]]);
  6052.         if ($etat == null) {
  6053.             return new Response(json_encode(([
  6054.                 'message' => 'Error, no etat found at this id',
  6055.                 'path' => 'src/Controller/RdvController.php',
  6056.                 "status" => 400,
  6057.             ])), 400);
  6058.         }
  6059.         $rdv->setIdEtat($etat);
  6060.         $rdv->setDuration($data["duree"]);
  6061.         $rdv->setIsAbsence($data["is_absence"]);
  6062.         $rdv->setMotifAbsence($data["motif"]);
  6063.         $rdv->setColor($data["color"]);
  6064.         $rdv->setNote($data["note"]);
  6065.         $rdv->setCacher(0);
  6066.         $entityManager $this->getDoctrine()->getManager();
  6067.         $entityManager->persist($rdv);
  6068.         $entityManager->flush();
  6069.         $this->mercure->publishRdvUpdate($rdv'created');
  6070.         // create google calendar absence event
  6071.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  6072.             ->findBy(array('audio' => $audio->getId()));
  6073.         $data['rdv'] = $rdv->getId();
  6074.         $data['motif_absence'] = $rdv->getMotifAbsence() !== '' $rdv->getMotifAbsence() : "Absence";
  6075.         //        dd($data);
  6076.         foreach ($synchronisations as $synchronisation) {
  6077.             if (!$synchronisation->getIsDeleted()) {
  6078.                 try {
  6079.                     $googleCalendar->checkAndRefreshAccessToken($synchronisation);
  6080.                     $googleCalendar->createAbsenceEvent($synchronisation$data);
  6081.                 } catch (\Google\Service\Exception $e) {
  6082.                     if ($e->getCode() === 403 && str_contains($e->getMessage(), 'insufficientPermissions')) {
  6083.                         error_log("Skipped synchronisation ID {$synchronisation->getId()} due to insufficient permissions.");
  6084.                         continue;
  6085.                     }
  6086.                     throw $e;
  6087.                 }
  6088.             }
  6089.         }
  6090.         return new Response(json_encode(([
  6091.             "id" => $rdv->getId(),
  6092.             "audio_id" => $rdv->getIdAudio()->getId(),
  6093.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  6094.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  6095.             "duration" => $data["duree"],
  6096.             "etat_id" => $rdv->getIdEtat()->getId(),
  6097.             "date" => $rdv->getDate(),
  6098.             "status" => 200,
  6099.         ])));
  6100.     }
  6101.     /**
  6102.      * @Route("/rdv/{id}/absence", name="puttAbsenceCalendar", methods={"PUT"})
  6103.      */
  6104.     public function putAbsenceCalendar(Request $requestRdv $rdvPublicFunction $publicFunctionGoogleCalendarService $googleCalendar): Response
  6105.     {
  6106.         $data json_decode($request->getContent(), true);
  6107.         if (!isset($data["token"])) {
  6108.             return new Response(json_encode([
  6109.                 "message" => "Pas de token n'a été spécifié",
  6110.                 "status" => 401,
  6111.             ]), 401);
  6112.         }
  6113.         $entityManager $this->getDoctrine()->getManager();
  6114.         /** @var Token */
  6115.         $token $this->getDoctrine()
  6116.             ->getRepository(Token::class)
  6117.             ->findOneBy(['token' => $data["token"]]);
  6118.         if (!$token) {
  6119.             return new Response(json_encode([
  6120.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  6121.                 "status" => 404,
  6122.             ]), 404);
  6123.         }
  6124.         // get token age
  6125.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  6126.         // if the token if older than 7 days
  6127.         if ($dateDiff->7) {
  6128.             $entityManager->remove($token);
  6129.             $entityManager->flush();
  6130.             return $this->json([
  6131.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  6132.                 'path' => 'src/Controller/ClientController.php',
  6133.                 "status" => 401,
  6134.             ], 401);
  6135.         }
  6136.         // remove the taken schedule by rdv to make sure there is no overlap
  6137.         if (isset($data["date"])) {
  6138.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  6139.             $rdv->setDate($date);
  6140.         }
  6141.         if (isset($data["duree"])) {
  6142.             $rdv->setDuration($data["duree"]);
  6143.         }
  6144.         if (isset($data["motif"])) {
  6145.             $rdv->setMotifAbsence($data["motif"]);
  6146.         }
  6147.         if (isset($data["color"])) {
  6148.             $rdv->setColor($data["color"]);
  6149.         }
  6150.         if (isset($data["note"])) {
  6151.             $rdv->setNote($data["note"]);
  6152.         }
  6153.         $entityManager $this->getDoctrine()->getManager();
  6154.         $entityManager->flush();
  6155.         $this->mercure->publishRdvUpdate($rdv'updated');
  6156.         $data['rdv'] = $rdv->getId();
  6157.         $data['motif_absence'] = $rdv->getMotifAbsence() !== '' $rdv->getMotifAbsence() : "Absence";
  6158.         $data['note'] = $rdv->getNote();
  6159.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  6160.             ->findBy(array('rdv' => $rdv));
  6161.         foreach ($rdvEvents as $rdvEvent) {
  6162.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  6163.             $googleCalendar->updateAbsenceEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
  6164.         }
  6165.         return new Response(json_encode(([
  6166.             "id" => $rdv->getId(),
  6167.             "audio_id" => $rdv->getIdAudio()->getId(),
  6168.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  6169.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  6170.             "duration" => $rdv->getDuration(),
  6171.             "etat_id" => $rdv->getIdEtat()->getId(),
  6172.             "date" => $rdv->getDate(),
  6173.             "status" => 200,
  6174.         ])));
  6175.     }
  6176.     /**
  6177.      * @Route("/rdv/{id}/calendar", name="editRdvCalendarByID", methods={"PUT"})
  6178.      */
  6179.     public function editRdvCalendarByID(SmsHandler $smsHandlerRdv $rdvRequest $requestGoogleCalendarService $googleCalendarPublicFunction $publicFunctionRdvSmsService $rdvSms): Response
  6180.     {
  6181.         $pastDate $rdv->getDate();
  6182.         $data json_decode($request->getContent(), true);
  6183.         $entityManager $this->getDoctrine()->getManager();
  6184.         if (!isset($data["token"])) {
  6185.             return new Response(json_encode([
  6186.                 "message" => "Pas de token n'a été spécifié",
  6187.                 "status" => 401,
  6188.             ]), 401);
  6189.         }
  6190.         /** @var Token */
  6191.         $token $this->getDoctrine()
  6192.             ->getRepository(Token::class)
  6193.             ->findOneBy(['token' => $data["token"]]);
  6194.         if (!$token) {
  6195.             return new Response(json_encode([
  6196.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  6197.                 "status" => 404,
  6198.             ]), 404);
  6199.         }
  6200.         // get token age
  6201.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  6202.         // if the token if older than 7 days
  6203.         if ($dateDiff->7) {
  6204.             $entityManager->remove($token);
  6205.             $entityManager->flush();
  6206.             return $this->json([
  6207.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  6208.                 'path' => 'src/Controller/ClientController.php',
  6209.                 "status" => 401,
  6210.             ], 401);
  6211.         }
  6212.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  6213.             return new Response(json_encode([
  6214.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  6215.                 "status" => 404,
  6216.             ]), 404);
  6217.         }
  6218.         if (isset($data["etat_id"])) {
  6219.             $etat $this->getDoctrine()
  6220.                 ->getRepository(EtatRdv::class)
  6221.                 ->findOneBy(['id' => $data["etat_id"]]);
  6222.             if ($etat == null) {
  6223.                 return new Response(json_encode(([
  6224.                     'message' => 'Error, no etat found at this id',
  6225.                     'path' => 'src/Controller/TrustedUserController.php',
  6226.                     "status" => 400,
  6227.                 ])), 400);
  6228.             }
  6229.             $rdv->setIdEtat($etat);
  6230.         }
  6231.         if (isset($data["audio_id"])) {
  6232.             $audio $this->getDoctrine()
  6233.                 ->getRepository(Audio::class)
  6234.                 ->findOneBy(['id' => $data["audio_id"]]);
  6235.             if ($audio == null) {
  6236.                 return new Response(json_encode(([
  6237.                     'message' => 'Error, no audio found at this id',
  6238.                     'path' => 'src/Controller/TrustedUserController.php',
  6239.                     "status" => 400,
  6240.                 ])), 400);
  6241.             }
  6242.             $rdv->setIdAudio($audio);
  6243.         }
  6244.         if (isset($data["motif_id"])) {
  6245.             $motif $this->getDoctrine()
  6246.                 ->getRepository(Motif::class)
  6247.                 ->find($data["motif_id"]);
  6248.             if ($motif == null) {
  6249.                 return new Response(json_encode(([
  6250.                     'message' => 'Error, no motif found at this id',
  6251.                     'path' => 'src/Controller/TrustedUserController.php',
  6252.                     "status" => 400,
  6253.                 ])), 400);
  6254.             }
  6255.             $rdv->setIdMotif($motif);
  6256.         }
  6257.         if (isset($data["client_id"])) {
  6258.             $client $this->getDoctrine()
  6259.                 ->getRepository(Client::class)
  6260.                 ->findOneBy(['id' => $data["client_id"]]);
  6261.             if ($client == null) {
  6262.                 return new Response(json_encode(([
  6263.                     'message' => 'Error, no client found at this id',
  6264.                     'path' => 'src/Controller/TrustedUserController.php',
  6265.                     "status" => 400,
  6266.                 ])), 400);
  6267.             }
  6268.             $rdv->setIdClient($client);
  6269.         }
  6270.         if (isset($data["date"])) {
  6271.             // remove the taken schedule by rdv to make sure there is no overlap
  6272.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  6273.             $audioMotif $this->getDoctrine()
  6274.                 ->getRepository(AudioMotif::class)
  6275.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  6276.             if ($audioMotif == null) {
  6277.                 return new Response(json_encode(([
  6278.                     'message' => 'Error, no motif of this id found at this audio',
  6279.                     'path' => 'src/Controller/RdvController.php',
  6280.                     "status" => 400,
  6281.                 ])), 400);
  6282.             }
  6283.             if ($rdv->getIdAudio()->getIsIndie()) {
  6284.                 if ($rdv->getIdCentre()) {
  6285.                     // regular centre audio indie
  6286.                     /** @var AudioCentre */
  6287.                     $liaison $this->getDoctrine()
  6288.                         ->getRepository(AudioCentre::class)
  6289.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  6290.                     if ($liaison == null) {
  6291.                         return new Response(json_encode(([
  6292.                             'message' => 'Error, audio isnt part of the centre',
  6293.                             'path' => 'src/Controller/RdvController.php',
  6294.                             "status" => 400,
  6295.                         ])), 400);
  6296.                     }
  6297.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  6298.                         return new Response(json_encode(([
  6299.                             'message' => 'Error, no horaire found for this audio',
  6300.                             'path' => 'src/Controller/RdvController.php',
  6301.                             "status" => 400,
  6302.                         ])), 400);
  6303.                     }
  6304.                 } else {
  6305.                     // lieu audio indie
  6306.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  6307.                         return new Response(json_encode(([
  6308.                             'message' => 'Error, no horaire found for this audio',
  6309.                             'path' => 'src/Controller/RdvController.php',
  6310.                             "status" => 400,
  6311.                         ])), 400);
  6312.                     }
  6313.                 }
  6314.             } else {
  6315.                 // regular centre
  6316.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  6317.                     return new Response(json_encode(([
  6318.                         'message' => 'Error, no horaire found for this audio',
  6319.                         'path' => 'src/Controller/RdvController.php',
  6320.                         "status" => 400,
  6321.                     ])), 400);
  6322.                 }
  6323.             }
  6324.             $rdv->setDate($date);
  6325.         }
  6326.         if (isset($data["comment"]) && $token->getIdClient()) {
  6327.             $rdv->setComment($data["comment"]);
  6328.         }
  6329.         if (isset($data["review"]) && $token->getIdClient()) {
  6330.             $rdv->setReview($data["review"]);
  6331.         }
  6332.         if (isset($data["note"])) {
  6333.             $rdv->setNote($data["note"]);
  6334.         }
  6335.         $entityManager->flush();
  6336.         $this->mercure->publishRdvUpdate($rdv'updated');
  6337.         $date $rdv->getDate();
  6338.         $smsDate $date->format('d-m-Y H:i');
  6339.         $oldDate $pastDate->format('d-m-Y H:i');
  6340.         $locale 'fr_FR';
  6341.         $formatter = new IntlDateFormatter(
  6342.             $locale,
  6343.             IntlDateFormatter::FULL,
  6344.             IntlDateFormatter::SHORT,
  6345.             null,
  6346.             IntlDateFormatter::GREGORIAN,
  6347.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  6348.         );
  6349.         $smsDateLongFormat $formatter->format($date);
  6350.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  6351.         $frenchDate ucfirst($frenchDate);
  6352.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  6353.         // notif client
  6354.         if ($rdv->getIdEtat()->getId() != 2) {
  6355.             $params = array(
  6356.                 "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  6357.                 "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  6358.                 "date" => $smsDateLongFormat,
  6359.                 "heure" => substr($smsDate1115),
  6360.                 "motif" => $rdv->getIdMotif()->getTitre(),
  6361.                 "centerName" => $rdv->getIdCentre()->getName(),
  6362.                 "centerAddress" => $rdv->getIdCentre()->getAddress(),
  6363.                 "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  6364.                 "audioMail" => $rdv->getIdAudio()->getMail(),
  6365.                 "centerPhone" => $rdv->getIdCentre()->getPhone(),
  6366.                 "centerCity" => $rdv->getIdCentre()->getCity(),
  6367.                 "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  6368.                 'titre' => 'Votre rendez-vous est modifié pour le',
  6369.                 'frenchDate' => $frenchDate,
  6370.             );
  6371.             $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  6372.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject184);
  6373.             if ($data["sms"]) {
  6374.                 $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.";
  6375.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  6376.             }
  6377.         }
  6378.         //     //// == suppression
  6379.         else if ($rdv->getIdEtat()->getId() == 2) {
  6380.             $params = array(
  6381.                 "date" => substr($smsDate010),
  6382.                 "lien" => "{$_ENV['BASE_client']}search",
  6383.                 "heure" => substr($smsDate1115),
  6384.                 "patientName" => $client->getLastName(),
  6385.                 'titre' => 'Votre rendez-vous est annulé :',
  6386.                 'centerName' => $rdv->getIdCentre()->getName(),
  6387.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  6388.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  6389.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  6390.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  6391.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  6392.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  6393.                 'motif' => $rdv->getIdMotif()->getTitre(),
  6394.             );
  6395.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  6396.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject188);
  6397.             if ($data["sms"]) {
  6398.                 $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  6399.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  6400.             }
  6401.         }
  6402.         //notif Audio
  6403.         if ($rdv->getIdEtat()->getId() != 2) {
  6404.             if ($data["sms"]) {
  6405.                 $params = array(
  6406.                     "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  6407.                     "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  6408.                     "date" => substr($smsDate010),
  6409.                     "frenchDate" => $frenchDate,
  6410.                     "heure" => substr($smsDate1115),
  6411.                     'motif' => $rdv->getIdMotif()->getTitre(),
  6412.                     'clientPhone' => $client->getPhone(),
  6413.                     'clientNom' => $client->getLastname(),
  6414.                     'clientPrenom' => $client->getName(),
  6415.                     'clientCivilite' => $client->getCivilite(),
  6416.                     'clientPostal' => $client->getPostal(),
  6417.                     'clientMail' => $client->getMail(),
  6418.                     'centerName' => $rdv->getIdCentre()->getName(),
  6419.                     'centerPostal' => $rdv->getIdCentre()->getPostale(),
  6420.                     'centerCity' => $rdv->getIdCentre()->getCity(),
  6421.                     'centerAddress' => $rdv->getIdCentre()->getAddress(),
  6422.                     'idPatient' => $client->getId(),
  6423.                     'proUrl' => "{$_ENV['BASE_logiciel']}",
  6424.                     'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  6425.                     'titre' => 'Votre rendez-vous est modifié pour le :'
  6426.                 );
  6427.                 $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  6428.                 $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  6429.                 if ($rdv->getIdAudio()->getModifRdvMail()) {
  6430.                     $subject "🔀 Rendez-vous My Audio modifié du " $frenchDate " à " substr($smsDate1115);
  6431.                     $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject186);
  6432.                 }
  6433.                 if ($rdv->getIdAudio()->getModifRdvSms()) {
  6434.                     $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.";
  6435.                     // $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $phoneAudio);
  6436.                 }
  6437.             }
  6438.         } else if ($rdv->getIdEtat()->getId() == 2) {
  6439.             if ($data["sms"]) {
  6440.                 $params = array(
  6441.                     "date" => substr($smsDate010),
  6442.                     "lien" => "{$_ENV['BASE_client']}search",
  6443.                     "heure" => substr($smsDate1115),
  6444.                     "patientName" => $client->getLastName(),
  6445.                     'titre' => 'Votre rendez-vous est annulé :',
  6446.                     'centerName' => $rdv->getIdCentre()->getName(),
  6447.                     'centerPostal' => $rdv->getIdCentre()->getPostale(),
  6448.                     'centerCity' => $rdv->getIdCentre()->getCity(),
  6449.                     'centerAddress' => $rdv->getIdCentre()->getAddress(),
  6450.                     'centerPhone' => $rdv->getIdCentre()->getPhone(),
  6451.                     'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  6452.                     'audioMail' => $rdv->getIdAudio()->getMail(),
  6453.                     'motif' => $rdv->getIdMotif()->getTitre(),
  6454.                 );
  6455.                 $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  6456.                 $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  6457.                 if ($rdv->getIdAudio()->getModifRdvMail()) {
  6458.                     $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  6459.                     $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject188);
  6460.                 }
  6461.                 if ($rdv->getIdAudio()->getModifRdvSms()) {
  6462.                     $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.";
  6463.                     //$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $phoneAudio);
  6464.                 }
  6465.             }
  6466.         }
  6467.         /* generate sms notif on update */
  6468.         // update sms notification     
  6469.         $rdvSms->updateRdvSms($rdv);
  6470.         // google calendar update
  6471.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  6472.             ->findBy(array('audio' => $rdv->getIdAudio()));
  6473.         $data['rdv'] = $rdv->getId();
  6474.         $data['motif_id'] = $rdv->getIdMotif();
  6475.         $data['note'] = $rdv->getNote();
  6476.         if ($rdv->getIdClient() !== null) {
  6477.             $data["client_id"] = $rdv->getIdClient()->getId();
  6478.         }
  6479.         if ($rdv->getIdClientTemp() !== null) {
  6480.             $data["client_id_temp"] = $rdv->getIdClientTemp()->getId();
  6481.         }
  6482.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  6483.             ->findBy(array('rdv' => $rdv));
  6484.         foreach ($rdvEvents as $rdvEvent) {
  6485.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  6486.             $googleCalendar->updateEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
  6487.         }
  6488.         return new Response(json_encode(([
  6489.             "id" => $rdv->getId(),
  6490.             "motif_id" => $rdv->getIdMotif()->getId(),
  6491.             "audio_id" => $rdv->getIdAudio()->getId(),
  6492.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  6493.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  6494.             "fullName" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  6495.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  6496.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  6497.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  6498.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  6499.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  6500.             "centre_id" => $rdv->getIdCentre()->getId(),
  6501.             "centerName" => $rdv->getIdCentre()->getName(),
  6502.             "etat_id" => $rdv->getIdEtat()->getId(),
  6503.             "date" => $rdv->getDate(),
  6504.             "comment" => $rdv->getComment(),
  6505.             "note" => $rdv->getNote(),
  6506.             "review" => $rdv->getReview(),
  6507.             "status" => 200,
  6508.         ])));
  6509.     }
  6510.     /**
  6511.      * @Route("/rdv/{id}/absence", name="deletetAbsenceCalendar", methods={"DELETE"})
  6512.      */
  6513.     public function deletetAbsenceCalendar(Request $requestRdv $rdvGoogleCalendarService $googleCalendar): Response
  6514.     {
  6515.         $data json_decode($request->getContent(), true);
  6516.         if (!isset($data["token"])) {
  6517.             return new Response(json_encode([
  6518.                 "message" => "Pas de token n'a été spécifié",
  6519.                 "status" => 401,
  6520.             ]), 401);
  6521.         }
  6522.         $entityManager $this->getDoctrine()->getManager();
  6523.         /** @var Token */
  6524.         $token $this->getDoctrine()
  6525.             ->getRepository(Token::class)
  6526.             ->findOneBy(['token' => $data["token"]]);
  6527.         if (!$token) {
  6528.             return new Response(json_encode([
  6529.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  6530.                 "status" => 404,
  6531.             ]), 404);
  6532.         }
  6533.         // get token age
  6534.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  6535.         // if the token if older than 7 days
  6536.         if ($dateDiff->7) {
  6537.             $entityManager->remove($token);
  6538.             $entityManager->flush();
  6539.             return $this->json([
  6540.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  6541.                 'path' => 'src/Controller/ClientController.php',
  6542.                 "status" => 401,
  6543.             ], 401);
  6544.         }
  6545.         // delete google agenda event
  6546.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  6547.             ->findBy(array('rdv' => $rdv));
  6548.         //dd($rdvEvents);
  6549.         foreach ($rdvEvents as $rdvEvent) {
  6550.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  6551.             $googleCalendar->deleteEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId());
  6552.             $entityManager->remove($rdvEvent);
  6553.             $entityManager->flush();
  6554.         }
  6555.         $this->mercure->publishRdvDeletion($rdv);
  6556.         $entityManager->remove($rdv);
  6557.         $entityManager->flush();
  6558.         return new Response(json_encode(([
  6559.             "message" => "Absence Supprime",
  6560.             "status" => 200,
  6561.         ])));
  6562.     }
  6563.     /**
  6564.      * @Route("/rdvs/facturation/rdv", name="getMyRDV", methods={"GET"})
  6565.      */
  6566.     public function getMyRDV(Request $request): Response
  6567.     {
  6568.         /* $date = new DateTime();
  6569.         $minutes_to_add = 10;
  6570.         $date->add(new DateInterval('PT' . $minutes_to_add . 'M'));
  6571.         $date->setTimezone(new DateTimeZone('Europe/Paris'));
  6572.         $currentDate = $date->format('Y-m-d H:i:00');
  6573.         $toSend = $this->getDoctrine()->getRepository(Rdv::class)
  6574.             ->findRdvsIn10Mins($currentDate); 
  6575.         */
  6576.     }
  6577.     /**
  6578.      * @Route("/rdvs/facturation/lead", name="getMyLead", methods={"GET"})
  6579.      */
  6580.     public function getMyLead(Request $request): Response {}
  6581.     /**
  6582.      * @Route("/rdvs/total-count", name="getRdvCount", methods={"GET"})
  6583.      */
  6584.     public function getRdvCount(Request $request): Response
  6585.     {
  6586.         $rdvs $this->getDoctrine()->getRepository(Rdv::class)->findAll();
  6587.         return new Response(count($rdvs));
  6588.     }
  6589.     /**
  6590.      * @Route("/admin/update-relance/{id}", name="admin_update_relance", methods={"POST"})
  6591.      */
  6592.     public function updateRelance(Request $requestLeadRdv $leadEntityManagerInterface $em): JsonResponse
  6593.     {
  6594.         $data json_decode($request->getContent(), true);
  6595.         $relanceCount $data['relanceCount'] ?? null;
  6596.         if ($relanceCount !== null) {
  6597.             $lead->setRelanceCallCount((int)$relanceCount);
  6598.             $em->flush();
  6599.             return new JsonResponse(['success' => true]);
  6600.         }
  6601.         return new JsonResponse(['success' => false], 400);
  6602.     }
  6603.     /**
  6604.      * @Route("/rdv/lead", name="postLeadRdv", methods={"POST"})
  6605.      */
  6606.     public function postLeadRdv(Request $requestEntityManagerInterface $entityManagerPublicFunction $publicFunctionGoogleCalendarService $googleCalendar): Response
  6607.     {
  6608.         $data json_decode($request->getContent(), true);
  6609.         $today = new DateTime();
  6610.         try {
  6611.             $client null;
  6612.             // Gestion du client via token ou création
  6613.             if (!empty($data['clientToken'])) {
  6614.                 $token $entityManager->getRepository(Token::class)->findOneBy(['token' => $data['clientToken']]);
  6615.                 $client $token $token->getIdClient() : null;
  6616.             } elseif (!empty($data['client'])) {
  6617.                 $clientData $this->createOrGetClient($data['client']);
  6618.                 $client $entityManager->getRepository(Client::class)->find($clientData['id']);
  6619.             }
  6620.             if (!$client) {
  6621.                 return $this->json(["status" => 400"message" => "Client non trouvé ou invalide"], 400);
  6622.             }
  6623.             // Création du rendez-vous LeadRdv
  6624.             $rdvLead = new LeadRdv();
  6625.             $rdvLead->setClient($client);
  6626.             if (isset($data['titleLead'])) {
  6627.                 $rdvLead->setTitleLead($data['titleLead']);
  6628.             }
  6629.             if (isset($data['rangeAge'])) {
  6630.                 $rdvLead->setRangeAge($data['rangeAge']);
  6631.             }
  6632.             if (isset($data['situations'])) {
  6633.                 $rdvLead->setSituationsGene($data['situations']);
  6634.             }
  6635.             if (isset($data['equipe'])) {
  6636.                 $rdvLead->setEquipeAppareil($data['equipe']);
  6637.             }
  6638.             if (isset($data['durationEquipe'])) {
  6639.                 $rdvLead->setDurationEquipeAppareil($data['durationEquipe']);
  6640.             }
  6641.             if (isset($data['bilanAuditif'])) {
  6642.                 $rdvLead->setBilanAuditif($data['bilanAuditif']);
  6643.             }
  6644.             if (isset($data['ordonance'])) {
  6645.                 $rdvLead->setOrdonance($data['ordonance']);
  6646.             }
  6647.             if (isset($data['dateOrdonance'])) {
  6648.                 $rdvLead->setDateOrdonance($data['dateOrdonance']);
  6649.             }
  6650.             if (isset($data['canMove'])) {
  6651.                 $rdvLead->setCanMove($data['canMove']);
  6652.             }
  6653.             if (isset($data['traffic_source'])) {
  6654.                 $rdvLead->setTrafficSource($data['traffic_source']);
  6655.             }
  6656.             if (isset($data['article_name'])) {
  6657.                 $rdvLead->setTrafficLpVersion($data['article_name']);
  6658.             }
  6659.             if (isset($data['lp_version'])) {
  6660.                 $rdvLead->setTrafficArticleName($data['lp_version']);
  6661.             }
  6662.             if (isset($data['isNewLp'])) {
  6663.                 $rdvLead->setIsNewLp($data['isNewLp']);
  6664.                 $leadStatus $entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'demande_contact']);
  6665.                 if ($leadStatus) {
  6666.                     $rdvLead->setLeadStatus($leadStatus);
  6667.                 }
  6668.             }
  6669.             $rdvLead->setDate($today);
  6670.             if (!empty($data['audio'])) {
  6671.                 $audio $entityManager->getRepository(Audio::class)->find($data['audio']);
  6672.                 if ($audio) {
  6673.                     $rdvLead->setAudio($audio);
  6674.                 }
  6675.             }
  6676.             if ($client->getPostal()) {
  6677.                 $centerCount $this->getMatchingCentresCount($client->getPostal());
  6678.                 $rdvLead->setCentersCount($centerCount);
  6679.                 if ($centerCount == 0) {
  6680.                     $leadStatus $entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'hors_zone']);
  6681.                     if ($leadStatus) {
  6682.                         $rdvLead->setLeadStatus($leadStatus);
  6683.                     }
  6684.                 }
  6685.             }
  6686.             // Création du Token
  6687.             $tokenString $publicFunction->generateRandomString(30);
  6688.             $token = (new Token())
  6689.                 ->setCreationDate(new DateTime())
  6690.                 ->setToken($tokenString)
  6691.                 ->setIdClient($client);
  6692.             $entityManager->persist($rdvLead);
  6693.             $entityManager->persist($token);
  6694.             $entityManager->flush();
  6695.             return $this->json([
  6696.                 "id" => $client->getId(),
  6697.                 "idRdvLead" => $rdvLead->getId(),
  6698.                 "name" => $client->getName(),
  6699.                 "lastname" => $client->getLastname(),
  6700.                 "token" => $tokenString,
  6701.                 "code" => $clientData['password'],
  6702.                 "postalCode" => $client->getPostal() ?? null,
  6703.                 "status" => 200,
  6704.             ]);
  6705.         } catch (\Exception $e) {
  6706.             return $this->json(["status" => 500"message" => $e->getMessage()], 500);
  6707.         }
  6708.     }
  6709.     /**
  6710.      * @Route("/testGenerateVoice", name="testGenerateVoice", methods={"GET"})
  6711.      */
  6712.     public function testGenerateVoice(AppointmentCallService $service): Response
  6713.     {
  6714.         // TEST LOCAL$rdv = $this->entityManager->getRepository(Rdv::class)->find(6653);
  6715.         $rdv $this->entityManager->getRepository(Rdv::class)->find(2306);
  6716.         $lead $this->entityManager->getRepository(LeadRdv::class)->find(496);
  6717.         // $service->handleCallCenterAfterRdv(
  6718.         //     $rdv
  6719.         // );
  6720.         // $service->handleReminderCallToPatient(
  6721.         //     $rdv
  6722.         // );
  6723.         $service->handleEquipmentStatusCall($rdv);
  6724.         // $service->handleReminderCallToPatientOneHourBefore(
  6725.         //     $rdv
  6726.         // );
  6727.         // $service->handleCallToPatientAfterRdv(
  6728.         //     $rdv
  6729.         // );
  6730.         // $service->handleFollowupCall15Days($rdv);
  6731.         // $service->handleNewLeadCall($lead, "+33743393532");
  6732.         // $service->handleFollowupCall31Days($rdv);
  6733.         return new Response(json_encode([
  6734.             "status" => 200,
  6735.         ]), 200, ['Content-Type' => 'application/json']);
  6736.     }
  6737.     /**
  6738.      * @Route("/testSynthflow", name="testSynthflow", methods={"POST"})
  6739.      */
  6740.     public function testSynthflow(SynthflowService $service): Response
  6741.     {
  6742.         // TEST LOCAL
  6743.         $lead $this->entityManager->getRepository(LeadRdv::class)->find(496);
  6744.         $service->initiateCall($lead);
  6745.         return new Response(json_encode([
  6746.             "status" => 200,
  6747.         ]), 200, ['Content-Type' => 'application/json']);
  6748.     }
  6749.     /**
  6750.      * Private method to create a new client or get existing one by phone
  6751.      */
  6752.     private function createOrGetClient(array $data): array
  6753.     {
  6754.         $clientRepository $this->entityManager->getRepository(Client::class);
  6755.         // check sur le mail et phone
  6756.         $existingClient $clientRepository->findOneBy(['mail' => $data['email']]);
  6757.         if ($existingClient) {
  6758.             if ($existingClient->getPostal() !== $data['postalCode']) {
  6759.                 $existingClient->setPostal($data['postalCode']);
  6760.                 $this->entityManager->persist($existingClient);
  6761.                 $this->entityManager->flush();
  6762.             }
  6763.             return ['id' => $existingClient->getId(), 'password' => 'Votre mot de passe'];
  6764.         }
  6765.         $randomPassword $this->generateRandomPassword(12);
  6766.         $client = new Client();
  6767.         $client->setLastname($data['lastname']);
  6768.         $client->setBirthdate(null);
  6769.         $client->setName($data['firstname']);
  6770.         $client->setPhone($data['phone']);
  6771.         $client->setMail($data['email']);
  6772.         $client->setSignupDate(new \DateTime());
  6773.         $client->setPassword(password_hash($randomPasswordPASSWORD_DEFAULT));
  6774.         $client->setPostal($data['postalCode']);
  6775.         $client->setAddress($data['address'] ?? null);
  6776.         $client->setCity($data['city'] ?? null);
  6777.         $client->setDesactivate(false);
  6778.         if (isset($data['civilite'])) {
  6779.             $civilite = ($data['civilite'] === 'Homme') ? 'Monsieur' 'Madame';
  6780.             $client->setCivilite($civilite);
  6781.         }
  6782.         $this->entityManager->persist($client);
  6783.         $this->entityManager->flush();
  6784.         return ['id' => $client->getId(), 'password' => $randomPassword];
  6785.     }
  6786.     private function generateRandomPassword($length 10): string
  6787.     {
  6788.         return bin2hex(random_bytes($length 2));
  6789.     }
  6790.     private function getMatchingCentresCount($clientPostal): int
  6791.     {
  6792.         // Récupérer les coordonnées GPS du code postal du client
  6793.         $clientCoordinates $this->entityManager
  6794.             ->getRepository(RegionDepartment::class)
  6795.             ->findOneBy(['codePostal' => $clientPostal]);
  6796.         $clientLat $clientCoordinates $clientCoordinates->getLatitude() : null;
  6797.         $clientLon $clientCoordinates $clientCoordinates->getLongitude() : null;
  6798.         $centres $this->entityManager->getRepository(Centre::class)->findAll();
  6799.         $count 0;
  6800.         foreach ($centres as $centre) {
  6801.             if ($centre->getZoneKm()) {
  6802.                 $latitude $centre->getLatitude();
  6803.                 $longitude $centre->getLongitude();
  6804.                 $radius $centre->getZoneKm();
  6805.                 $postals $this->entityManager->getRepository(RegionDepartment::class)->findPostalsWithinRadius($latitude$longitude$radius);
  6806.                 $postalCodes array_values(array_unique(array_column($postals'code_postal')));
  6807.                 if (in_array($clientPostal$postalCodes)) {
  6808.                     $count++;
  6809.                 }
  6810.             }
  6811.         }
  6812.         return $count;
  6813.     }
  6814.     /**
  6815.      * @Route("/rdv/send-map", name="getRdvMap", methods={"POST"})
  6816.      */
  6817.     public function sendEmailWithMap(Request $requestPublicFunction $publicFunction): Response
  6818.     {
  6819.         $data json_decode($request->getContent(), true);
  6820.         $mail "";
  6821.         $name "";
  6822.         $centre "";
  6823.         if (isset($data['clientToken'])) {
  6824.             $token $this->getDoctrine()->getRepository(Token::class)->findOneBy(['token' => $data['clientToken']]);
  6825.             $client $token->getIdClient();
  6826.             $mail $client->getMail();
  6827.             $name $client->getLastname() . " " $client->getName();
  6828.             $centre $this->getDoctrine()->getRepository(Centre::class)->findOneBy(['id' => $data['centre']['id']]);
  6829.         } else {
  6830.             $mail $data['email'];
  6831.             $name $data['name'];
  6832.         }
  6833.         $locale 'fr_FR';
  6834.         $dateTime DateTime::createFromFormat('d/m/Y H:i'$data['date']);
  6835.         if ($dateTime) {
  6836.             $fmt = new IntlDateFormatter($localeIntlDateFormatter::FULLIntlDateFormatter::NONE);
  6837.             $fmt->setPattern("EEEE dd MMMM");
  6838.             $formattedDate ucfirst($fmt->format($dateTime));
  6839.         } else {
  6840.             $formattedDate "Date invalide";
  6841.         }
  6842.         $params = [
  6843.             'date' => $data['date'],
  6844.             'time' => $data['time'],
  6845.             'frenchDate' => $formattedDate,
  6846.             'clientAddress' => $data['address'],
  6847.             'centerName' => $centre->getName(),
  6848.             'centerAddress' => $centre->getAddress(),
  6849.             'centerPostal' => $centre->getPostale(),
  6850.             'centerCity' => $centre->getCity(),
  6851.             'start' => $data['start'],
  6852.             'end' => $data['end'],
  6853.             'urlApi' => "{$_ENV['BASE_client']}",
  6854.         ];
  6855.         $publicFunction->sendEmail($params$mail$name"Votre Rendez-vous My Audio"198);
  6856.         return new Response(json_encode([
  6857.             "status" => 200,
  6858.             "params" => $params,
  6859.         ]), 200, ['Content-Type' => 'application/json']);
  6860.     }
  6861.     /**
  6862.      * @Route("/rdv/cantmove", name="notifCantMove", methods={"POST"})
  6863.      */
  6864.     public function notifCantMove(Request $requestPublicFunction $publicFunction): Response
  6865.     {
  6866.         $data json_decode($request->getContent(), true);
  6867.         $email "lead.myaudio@gmail.com";
  6868.         $centre "";
  6869.         $type "My Audio";
  6870.         $details "";
  6871.         $picto "❌";
  6872.         $ordo "sans ordo";
  6873.         $subject "";
  6874.         if (isset($data['ordonance'])) {
  6875.             if ($data["ordonance"] == "oui") {
  6876.                 $ordo "avec ordo";
  6877.             }
  6878.         } else {
  6879.             $ordo "";
  6880.         }
  6881.         if (isset($data['centre'])) {
  6882.             $centre $data['centre'];
  6883.             $subject $picto " Lead - demande de contact ne pouvant pas se déplacer " $data['postal'] . " " $ordo;
  6884.         } else {
  6885.             $centre "";
  6886.             $type "Hors Zone";
  6887.             $details "Pas de centre dans la zone";
  6888.             $subject $picto " Lead Hors Zone " $data['postal'] . " " $ordo " ne pouvant pas se déplacer";
  6889.         }
  6890.         $responses = [
  6891.             'rangeAge' => isset($data['rangeAge']) ? $data['rangeAge'] : null,
  6892.             'situations' => isset($data['situations']) ? $data['situations'] : null,
  6893.             'equipeAppareil' => isset($data['equipe']) ? $data['equipe'] : null,
  6894.             'durationEquipe' => isset($data['durationEquipe']) ? $data['durationEquipe'] : null,
  6895.             'bilanAuditif' => isset($data['bilanAuditif']) ? $data['bilanAuditif'] : null,
  6896.             'ordonance' => isset($data['ordonance']) ? $data['ordonance'] : null,
  6897.             'dateOrdonance' => isset($data['dateOrdonance']) ? $data['dateOrdonance'] : null,
  6898.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  6899.         ];
  6900.         $department $this->getDepartmentFromPostalCode($data['address']);
  6901.         $data['departmentCode'] = $department['departmentCode'];
  6902.         $data['departmentName'] = $department['departmentName'];
  6903.         $data['regionName'] = $department['regionName'];
  6904.         $data['city'] = $department['city'];
  6905.         $params = [
  6906.             'date' => $data['date'],
  6907.             'time' => $data['time'],
  6908.             'address' => $data['address'],
  6909.             'centre' => $centre,
  6910.             'type' => $type,
  6911.             'details' => $details,
  6912.             'responses' => $responses,
  6913.             'name' => $data['name'],
  6914.             'civilite' => $data['civilite'],
  6915.             'nom' => $data['firstname'],
  6916.             'prenom' => $data['lastname'],
  6917.             'codePostal' => $data['address'],
  6918.             'telephone' => $data['phone'],
  6919.             'email' => $data['email'],
  6920.             'departement' => $data['departmentName'],
  6921.             'ville' => $data['city'],
  6922.             'region' => $data['regionName'],
  6923.             'trangeAge' => isset($data['rangAge']) ? $data['rangAge'] : null,
  6924.             'situationVecu' => isset($data['situations']) ? implode(', '$data['situations']) : null,
  6925.             'dejaEquipe' => isset($data['equipeAppareil']) ? $data['equipeAppareil'] : null,
  6926.             'trafficSource' => isset($data['traffic_source']) ? $data['traffic_source'] : null,
  6927.             'articleName' => isset($data['article_name']) ? $data['article_name'] : null,
  6928.             'lpVersion' => isset($data['lp_version']) ? $data['lp_version'] : null,
  6929.         ];
  6930.         $publicFunction->sendEmail($params$email$data['name'], $subject208);
  6931.         return new Response(json_encode([
  6932.             "status" => 200,
  6933.         ]), 200, ['Content-Type' => 'application/json']);
  6934.     }
  6935.     /**
  6936.      * @Route("/rdv/cantmove/v2", name="notifCantMoveV2", methods={"POST"})
  6937.      */
  6938.     public function notifCantMoveV2(Request $requestPublicFunction $publicFunction): Response
  6939.     {
  6940.         $data json_decode($request->getContent(), true);
  6941.         $email "lead.myaudio@gmail.com";
  6942.         $centre "";
  6943.         $type "My Audio";
  6944.         $details "";
  6945.         $picto "❌";
  6946.         $subject "";
  6947.         $audio "";
  6948.         $subject $picto " Lead ne pouvant pas se déplacer";
  6949.         $department $this->getDepartmentFromPostalCode($data['address']);
  6950.         $data['departmentCode'] = $department['departmentCode'];
  6951.         $data['departmentName'] = $department['departmentName'];
  6952.         $data['regionName'] = $department['regionName'];
  6953.         $data['city'] = $department['city'];
  6954.         $password "";
  6955.         $params = [
  6956.             'name' => $data['name'],
  6957.             'civilite' => $data['civilite'],
  6958.             'nom' => $data['firstname'],
  6959.             'prenom' => $data['lastname'],
  6960.             'codePostal' => $data['address'],
  6961.             'telephone' => $data['phone'],
  6962.             'email' => $data['email'],
  6963.             'password' => $data['clientSecretCookie'],
  6964.             'trancheAge' => isset($data['rangAge']) ? $data['rangAge'] : null,
  6965.             'situationVecu' => isset($data['situations']) ? implode(', '$data['situations']) : null,
  6966.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  6967.             'trafficSource' => isset($data['traffic_source']) ? $data['traffic_source'] : null,
  6968.             'articleName' => isset($data['article_name']) ? $data['article_name'] : null,
  6969.             'lpVersion' => isset($data['lp_version']) ? $data['lp_version'] : null,
  6970.             'urlLogin' => "{$_ENV['BASE_client']}login"
  6971.         ];
  6972.         // Send email to MyAudio
  6973.         $publicFunction->sendEmail($params$email$data['name'], $subject220);
  6974.         $publicFunction->sendEmail($params'contact@myaudio.fr'$data['name'], $subject220);
  6975.         // Send email to patient
  6976.         $params = [
  6977.             'clientEmail' => $data['email'],
  6978.             'clientPassword' => $data['clientSecretCookie'],
  6979.             'rdv' => "https://www.myaudio.fr/search",
  6980.             'urlLogin' => "{$_ENV['BASE_client']}login"
  6981.         ];
  6982.         $publicFunction->sendEmail($params$data['email'], $data['name'], 'Rendez-vous My Audio - En cours de traitement'219);
  6983.         $rdvLead $this->entityManager->getRepository(LeadRdv::class)->find($data['clientRdvLp']);
  6984.         if ($rdvLead) {
  6985.             $leadStatus $this->entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'cant_move']);
  6986.             if ($leadStatus) {
  6987.                 $rdvLead->setLeadStatus($leadStatus);
  6988.                 $this->entityManager->flush();
  6989.             }
  6990.         }
  6991.         return new Response(json_encode([
  6992.             "status" => 200,
  6993.         ]), 200, ['Content-Type' => 'application/json']);
  6994.     }
  6995.     /**
  6996.      * @Route("/rdv/notiflead", name="notifLead", methods={"POST"})
  6997.      */
  6998.     public function notifLeadRdv(Request $requestPublicFunction $publicFunction): Response
  6999.     {
  7000.         $data json_decode($request->getContent(), true);
  7001.         $email "lead.myaudio@gmail.com";
  7002.         $centre "";
  7003.         $type "My Audio";
  7004.         $details "";
  7005.         $picto "❌";
  7006.         $ordo "sans ordo";
  7007.         $subject "";
  7008.         $name "";
  7009.         $postal "";
  7010.         $emailPatient "";
  7011.         if (isset($data['clientToken']) && !empty($data['clientToken'])) {
  7012.             $token $this->getDoctrine()->getRepository(Token::class)->findOneBy(['token' => $data['clientToken']]);
  7013.             $client $token->getIdClient();
  7014.             $name $client->getLastname() . " " $client->getName();
  7015.             $postal $client->getPostal();
  7016.             $emailPatient $client->getMail();
  7017.         } else {
  7018.             if (isset($data['postal'])) {
  7019.                 $postal $data['postal'];
  7020.             }
  7021.             if (isset($data['name'])) {
  7022.                 $name $data['name'];
  7023.             }
  7024.             if (isset($data['email'])) {
  7025.                 $email $data['email'];
  7026.             }
  7027.             if (isset($data['email'])) {
  7028.                 $emailPatient $data['email'];
  7029.             }
  7030.         }
  7031.         if (isset($data["ordonance"])) {
  7032.             if ($data["ordonance"] == "oui") {
  7033.                 $ordo "avec ordo";
  7034.             }
  7035.         }
  7036.         if (isset($data['centre'])) {
  7037.             $centre $data['centre'];
  7038.             $picto "✅";
  7039.             $subject $picto " Lead booké " $postal " " $ordo;
  7040.         } else {
  7041.             $centre "";
  7042.             $type "Hors Zone";
  7043.             $details "Pas de centre dans la zone";
  7044.             $subject $picto " Lead Hors Zone " $postal " " $ordo;
  7045.         }
  7046.         $responses = [
  7047.             'rangeAge' => isset($data['rangeAge']) ? $data['rangeAge'] : null,
  7048.             'situations' => isset($data['situations']) ? $data['situations'] : null,
  7049.             'equipeAppareil' => isset($data['equipe']) ? $data['equipe'] : null,
  7050.             'durationEquipe' => isset($data['durationEquipe']) ? $data['durationEquipe'] : null,
  7051.             'bilanAuditif' => isset($data['bilanAuditif']) ? $data['bilanAuditif'] : null,
  7052.             'ordonance' => isset($data['ordonance']) ? $data['ordonance'] : null,
  7053.             'dateOrdonance' => isset($data['dateOrdonance']) ? $data['dateOrdonance'] : null,
  7054.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  7055.         ];
  7056.         $params = [
  7057.             'date' => $data['date'],
  7058.             'time' => $data['time'],
  7059.             'address' => $data['address'],
  7060.             'centre' => $centre,
  7061.             'type' => $type,
  7062.             'details' => $details,
  7063.             'responses' => $responses,
  7064.             'name' => $name,
  7065.             'email' => $emailPatient,
  7066.         ];
  7067.         $publicFunction->sendEmail($params$email$name$subject180);
  7068.         return new Response(json_encode([
  7069.             "status" => 200,
  7070.             "params" => $params,
  7071.             "responses" => $responses
  7072.         ]), 200, ['Content-Type' => 'application/json']);
  7073.     }
  7074.     /**
  7075.      *  Met à jour l'état d'un rendez-vous.
  7076.      *
  7077.      * Cette fonction permet de modifier l'état d'un rendez-vous en fonction des données envoyées
  7078.      * via une requête PUT. Elle effectue plusieurs vérifications, notamment :
  7079.      * - La présence et la validité du token d'authentification.
  7080.      * - L'existence du rendez-vous et du nouvel état.
  7081.      * - L'expiration du token (plus de 7 jours).
  7082.      * 
  7083.      * Si le rendez-vous est marqué comme "Absence injustifiée" (état ID 3), un email et un SMS sont envoyés
  7084.      * au client et à l'équipe MyAudio pour les informer.
  7085.      * 
  7086.      * @Route("api/save-etat-rdv", name="saveEtatRdv", methods={"PUT"})
  7087.      */
  7088.     public function saveEtatRdv(Request $requestPublicFunction $publicFunction): Response
  7089.     {
  7090.         $entityManager $this->getDoctrine()->getManager();
  7091.         $data json_decode($request->getContent(), true);
  7092.         if (!$data['token']) {
  7093.             return new Response(json_encode([
  7094.                 "message" => "Pas de token n'a été spécifié",
  7095.                 "status" => 401,
  7096.             ]), 401);
  7097.         }
  7098.         /** @var Token */
  7099.         $token $this->getDoctrine()
  7100.             ->getRepository(Token::class)
  7101.             ->findOneBy(['token' => $data['token'], 'id_audio' => $data['audio']]);
  7102.         if (!$token) {
  7103.             return new Response(json_encode([
  7104.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  7105.                 "status" => 404,
  7106.             ]), 404);
  7107.         }
  7108.         // get token age
  7109.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  7110.         // if the token if older than 7 days
  7111.         if ($dateDiff->7) {
  7112.             $entityManager->remove($token);
  7113.             $entityManager->flush();
  7114.             return $this->json([
  7115.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  7116.                 'path' => 'src/Controller/ClientController.php',
  7117.                 "status" => 401,
  7118.             ], 401);
  7119.         }
  7120.         $rdv $this->getDoctrine()->getRepository(Rdv::class)->find($data['rdv']);
  7121.         if (!$rdv) {
  7122.             return new Response(json_encode([
  7123.                 "message" => "Rdv not found.",
  7124.                 "status" => 404,
  7125.             ]), 404);
  7126.         }
  7127.         $rdvEtat $this->getDoctrine()
  7128.             ->getRepository(EtatRdv::class)
  7129.             ->find($data['etat']);
  7130.         if (!$rdvEtat) {
  7131.             return new Response(json_encode([
  7132.                 "message" => "Rdv etat not found.",
  7133.                 "status" => 404,
  7134.             ]), 404);
  7135.         }
  7136.         $rdv->setIdEtat($rdvEtat);
  7137.         $entityManager->flush();
  7138.         $encodedNomDuCentre rawurlencode($rdv->getIdCentre()->getName());
  7139.         $urlApi "audioprothesiste/{$rdv->getIdCentre()->getCity()}/{$rdv->getIdCentre()->getPostale()}/{$encodedNomDuCentre}/prise-de-rdvaudioprothesiste-rapide/{$rdv->getIdCentre()->getId()}";
  7140.         if ($rdvEtat->getId() == 3) {
  7141.             // Send email to client
  7142.             $date $rdv->getDate();
  7143.             $smsDate $date->format('d-m-Y H:i');
  7144.             $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  7145.             $params = array(
  7146.                 "date" => substr($smsDate010),
  7147.                 "lien" => "{$_ENV['BASE_client']}$urlApi,
  7148.                 "heure" => substr($smsDate1115),
  7149.                 'centerName' => $rdv->getIdCentre()->getName() ?? '',
  7150.                 'centerPostal' => $rdv->getIdCentre()->getPostale() ?? '',
  7151.                 'centerCity' => $rdv->getIdCentre()->getCity() ?? '',
  7152.                 'centerAddress' => $rdv->getIdCentre()->getAddress() ?? '',
  7153.                 'centerPhone' => $rdv->getIdCentre()->getPhone() ?? '',
  7154.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName() ?? '',
  7155.                 'audioMail' => $rdv->getIdAudio()->getMail() ?? '',
  7156.             );
  7157.             $subject "Vous avez manqué votre rendez-vous MyAudio avec " $rdv->getIdCentre()->getName();
  7158.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject214);
  7159.             // Send sms to client
  7160.             $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();
  7161.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  7162.             // Send email to MyAudio
  7163.             $date $rdv->getDate();
  7164.             $smsDate $date->format('d-m-Y H:i');
  7165.             $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  7166.             $params = array(
  7167.                 "date" => substr($smsDate010),
  7168.                 "lien" => "{$_ENV['BASE_client']}search",
  7169.                 "heure" => substr($smsDate1115),
  7170.                 'centerName' => $rdv->getIdCentre()->getName() ?? '',
  7171.                 'centerPostal' => $rdv->getIdCentre()->getPostale() ?? '',
  7172.                 'centerCity' => $rdv->getIdCentre()->getCity() ?? '',
  7173.                 'centerAddress' => $rdv->getIdCentre()->getAddress() ?? '',
  7174.                 'centerPhone' => $rdv->getIdCentre()->getPhone() ?? '',
  7175.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName() ?? '',
  7176.                 'audioMail' => $rdv->getIdAudio()->getMail() ?? '',
  7177.                 'clientName' => $client->getName() . ' ' $client->getLastName() ?? '',
  7178.                 'clientMail' => $client->getMail() ?? '',
  7179.                 'clientPhone' => $client->getPhone() ?? '',
  7180.             );
  7181.             $subject "Le patient " $client->getName() . ' ' $client->getLastName() . " a manqué son rendez-vous MyAudio avec le centre " $rdv->getIdCentre()->getName();
  7182.             $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$client->getName() . ' ' $client->getLastName(), $subject215);
  7183.         }
  7184.         return new Response(json_encode([
  7185.             "message" => "rdvEtat has been successfully updated",
  7186.             "status" => 200,
  7187.         ]));
  7188.     }
  7189.     /**
  7190.      * 
  7191.      * @Route("api/send-email/clientnotcompletebook", name="askToContact", methods={"POST"})
  7192.      */
  7193.     public function askToContact(Request $requestPublicFunction $publicFunction): Response
  7194.     {
  7195.         $data json_decode($request->getContent(), true);
  7196.         $staticToken "3f3a8b74f3e5b2d0c4917f5f9a7c07efb1a0f1e5e8c907ec9c4e9df129e3125e9";
  7197.         $token $data['token'] ?? null;
  7198.         if ($token !== $staticToken) {
  7199.             return new JsonResponse(
  7200.                 [
  7201.                     'status' => 'error',
  7202.                     'code' => 'unauthorized',
  7203.                     'message' => 'Unauthorized access.'
  7204.                 ],
  7205.                 JsonResponse::HTTP_UNAUTHORIZED
  7206.             );
  7207.         }
  7208.         $params = [
  7209.             'clientCivilite' => isset($data['civilite']) ? $data['civilite'] : 'Pas indiqué',
  7210.             'clientNom' => isset($data['firstname']) ? $data['firstname'] : null,
  7211.             'clientPrenom' => isset($data['lastname']) ? $data['lastname'] : null,
  7212.             'clientPostal' => isset($data['postalCode']) ? $data['postalCode'] : null,
  7213.             'clientPhone' => isset($data['phone']) ? $data['phone'] : null,
  7214.             'clientMail' => isset($data['email']) ? $data['email'] : null,
  7215.             'password' => isset($data['clientSecretCookie']) ? $data['clientSecretCookie'] : null,
  7216.             'rangeAge' => isset($data['trancheAge']) ? $data['trancheAge'] : null,
  7217.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  7218.             'situations' => isset($data['situations']) ? implode(', '$data['situations']) : null,
  7219.             'trafficSource' => isset($data['traffic_source']) ? $data['traffic_source'] : null,
  7220.             'articleName' => isset($data['article_name']) ? $data['article_name'] : null,
  7221.             'lpVersion' => isset($data['lp_version']) ? $data['lp_version'] : null,
  7222.         ];
  7223.         $templateEmailMyAudio 223;
  7224.         if (!empty($data['centre'])) {
  7225.             $centre $data['centre'];
  7226.             $audio $centre['audio'][0];
  7227.             $params['centerName'] = $centre['name'] ?? null;
  7228.             $params['centerPostal'] = $centre['postale'] ?? null;
  7229.             $params['centerCity'] = $centre['city'] ?? null;
  7230.             $params['centerAddress'] = $centre['address'] ?? null;
  7231.             $params['centerPhone'] = $centre['phone'] ?? null;
  7232.             $params['audioproName'] = $audio['civilite'] . ' ' $audio['lastname'] . ' ' $audio['name'] ?? null;
  7233.             $templateEmailMyAudio 222;
  7234.         }
  7235.         // Email to My Audio
  7236.         $email "lead.myaudio@gmail.com";
  7237.         $subject "Demande de contact -  Nouveau Lead À Contacter Hors Zone";
  7238.         $publicFunction->sendEmail($params$email$data['name'], $subject$templateEmailMyAudio);
  7239.         $publicFunction->sendEmail($params'contact@myaudio.fr'$data['name'], $subject$templateEmailMyAudio);
  7240.         $coordinates $this->getCoordinatesFromPostalCode($data['postalCode']);
  7241.         $latitude $coordinates['latitude'];
  7242.         $longitude $coordinates['longitude'];
  7243.         $params = [
  7244.             'email' => isset($data['email']) ? $data['email'] : null,
  7245.             'password' => isset($data['clientSecretCookie']) ? $data['clientSecretCookie'] : null,
  7246.             "lienRdv" => "{$_ENV['BASE_client']}search?latitude={$latitude}&longitude={$longitude}&ville={$data['postalCode']}",
  7247.         ];
  7248.         // Email to Client
  7249.         $subject "My Audio - Confirmation de demande de contact";
  7250.         $publicFunction->sendEmail($params$data['email'], $data['name'], $subject221);
  7251.         $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";
  7252.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$data['phone']);
  7253.         if (isset($data['clientRdvLp'])) {
  7254.             $rdvLead $this->entityManager->getRepository(LeadRdv::class)->find($data['clientRdvLp']);
  7255.             if ($rdvLead) {
  7256.                 $rdvLead->setSendAskToContact(1);
  7257.                 $rdvLead->setCountAskToContact(($rdvLead->getCountAskToContact() ?? 0) + 1);
  7258.                 $this->entityManager->flush();
  7259.                 $this->sendWhatsApp($data$rdvLead);
  7260.             }
  7261.         }
  7262.         return new Response(json_encode([
  7263.             "message" => "Email ask for contact send with success",
  7264.             "status" => 200,
  7265.         ]));
  7266.     }
  7267.     private function sendWhatsApp($data$lead): void
  7268.     {
  7269.         $adminUrl $this->adminUrlGenerator
  7270.             ->setDashboard(DashboardController::class)
  7271.             ->setController(LeadRdvCrudController::class)
  7272.             ->setAction('detail')
  7273.             ->setEntityId($lead->getId())
  7274.             ->generateUrl();
  7275.         $relativeUrl parse_url($adminUrlPHP_URL_PATH) . '?' parse_url($adminUrlPHP_URL_QUERY);
  7276.         // Supprimer le slash en trop s’il y en a un au début
  7277.         $relativeUrl ltrim($relativeUrl'/');
  7278.         // 🧑‍🤝‍🧑 Tableau des destinataires
  7279.         $destinataires = [
  7280.             '33611879183'// Numéro 1
  7281.             '33667597626'// Numéro 2
  7282.             '447884128220'// Numéro 3
  7283.         ];
  7284.         foreach ($destinataires as $numero) {
  7285.             $this->whatsapp->sendTemplateMessage(
  7286.                 $numero,  // Numéro de téléphone du destinataire
  7287.                 'lead_notif_myaudio',  // Nom du template WhatsApp
  7288.                 [
  7289.                     'body' => [
  7290.                         ['parameter_name' => 'nom_client''text' => $data['firstname'] . ' ' $data['lastname']],  // {{nom_client}}
  7291.                         ['parameter_name' => 'email_client''text' => $data['email'] ?? ' '],  // {{email_client}}
  7292.                         ['parameter_name' => 'telephone_client''text' => $data['phone'] ?? ' '],  // {{telephone_client}}
  7293.                         ['parameter_name' => 'date_lead''text' => $lead->getDate()->format('d/m/Y H:i')],  // {{date_lead}}
  7294.                         ['parameter_name' => 'code_postal''text' => $data['postalCode'] ?? ' '],  // {{code_postal}}
  7295.                         ['parameter_name' => 'nombre_centres''text' => $lead->getCentersCount() ?? '0'],  // {{nombre_centres}}
  7296.                     ],
  7297.                     'button' => $relativeUrl,  // <--- seulement le chemin dynamique
  7298.                 ]
  7299.             );
  7300.         }
  7301.     }
  7302.     /**
  7303.      * Get coordinates from the postal code using the database.
  7304.      */
  7305.     private function getCoordinatesFromPostalCode(string $postalCode): array
  7306.     {
  7307.         $region $this->entityManager
  7308.             ->getRepository(RegionDepartment::class)
  7309.             ->findOneBy(['codePostal' => $postalCode]);
  7310.         if ($region) {
  7311.             return [
  7312.                 'latitude' => $region->getLatitude(),
  7313.                 'longitude' => $region->getLongitude(),
  7314.             ];
  7315.         }
  7316.         return [
  7317.             'latitude' => null,
  7318.             'longitude' => null,
  7319.         ];
  7320.     }
  7321.     /**
  7322.      * Get the department code from the code postal
  7323.      */
  7324.     private function getDepartmentFromPostalCode(string $postalCode): ?array
  7325.     {
  7326.         $region $this->entityManager
  7327.             ->getRepository(RegionDepartment::class)
  7328.             ->findOneBy(['codePostal' => $postalCode]);
  7329.         if ($region) {
  7330.             return [
  7331.                 'departmentCode' => $region->getCodeDepartement(),
  7332.                 'departmentName' => $region->getNomDepartement(),
  7333.                 'regionCode' => $region->getCodeRegion(),
  7334.                 'regionName' => $region->getNomRegion(),
  7335.                 'city' => $region->getNomCommunePostal(),
  7336.             ];
  7337.         }
  7338.         return null;
  7339.     }
  7340.     /**
  7341.      * 
  7342.      * @Route("/giuili-admin/lead/{leadId}/centre/{centreId}", name="showLeadCentre", methods={"GET"})
  7343.      */
  7344.     public function showLeadCentre(int $leadIdCentre $centreId): Response
  7345.     {
  7346.         // dd("tets");
  7347.         $center $centres $this->getDoctrine()
  7348.             ->getRepository(AudioCentre::class)
  7349.             ->findOneBy(['id_centre' => $centreId->getId()]);
  7350.         $audio $center->getIdAudio();
  7351.         $motifs $this->getDoctrine()->getRepository(AudioMotif::class)
  7352.             ->findBy(['id_audio' => $audio'isDeleted' => 0]);
  7353.         return $this->render('easyadmin/leadRdv/centre_show.html.twig', [
  7354.             'audio' => $audio,
  7355.             'leadId' => $leadId,
  7356.             'centreId' => $centreId,
  7357.             'motifs' => $motifs,
  7358.         ]);
  7359.     }
  7360.     /**
  7361.      * @Route("/rdv-easyadmin", name="postRdvEasyAdmin", methods={"POST"})
  7362.      */
  7363.     public function postRdvEasyAdmin(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendarRdvSmsService $rdvSmsAppointmentCallService $Callservice): Response
  7364.     {
  7365.         $data json_decode($request->getContent(), true);
  7366.         $entityManager $this->getDoctrine()->getManager();
  7367.         $audio $this->getDoctrine()
  7368.             ->getRepository(Audio::class)
  7369.             ->findOneBy(['id' => $data["audio_id"]]);
  7370.         $leadRdv =   $this->getDoctrine()->getRepository(LeadRdv::class)
  7371.             ->find($data["lead_id"]);
  7372.         $client $this->getDoctrine()->getRepository(Client::class)
  7373.             ->find($leadRdv->getClient());
  7374.         $responses = [
  7375.             'rangeAge' => $leadRdv->getRangeAge(),
  7376.             'situations' =>  implode(", "$leadRdv->getSituationsGene()),
  7377.             'equipeAppareil' => $leadRdv->getEquipeAppareil(),
  7378.             'durationEquipe' => $leadRdv->getDurationEquipeAppareil(),
  7379.             'bilanAuditif' => $leadRdv->getBilanAuditif(),
  7380.             'ordonance' => $leadRdv->getOrdonance(),
  7381.             'dateOrdonance' => $leadRdv->getDateOrdonance(),
  7382.             'canMove' => $leadRdv->getCanMove(),
  7383.         ];
  7384.         // makes the rdv
  7385.         $rdv = new Rdv();
  7386.         $rdv->setIdAudio($audio);
  7387.         if (isset($proche)) {
  7388.             $rdv->setIdProche($proche);
  7389.         }
  7390.         if (isset($data["client_id_temp"])) {
  7391.             $rdv->setIdClientTemp($client);
  7392.         } else {
  7393.             $rdv->setIdClient($client);
  7394.         }
  7395.         $rdv->setIsMyaudio(true);
  7396.         if (isset($data["isRdvLead"])) {
  7397.             $rdv->setIsRdvLp(true);
  7398.         }
  7399.         if (isset($data["isRdvRapide"])) {
  7400.             $rdv->setIsRdvRapide(true);
  7401.         }
  7402.         if (isset($data["duree"])) {
  7403.             $rdv->setDuration($data["duree"]);
  7404.         }
  7405.         if (isset($data["color"])) {
  7406.             $rdv->setColor($data["color"]);
  7407.         }
  7408.         /** @var Centre */
  7409.         if (isset($data["centre_id"])) {
  7410.             $centre $this->getDoctrine()
  7411.                 ->getRepository(Centre::class)
  7412.                 ->findOneBy(['id' => $data["centre_id"]]);
  7413.             if ($centre == null) {
  7414.                 return new Response(json_encode(([
  7415.                     'message' => 'Error, no centre found at this id',
  7416.                     'path' => 'src/Controller/RdvController.php',
  7417.                     "status" => 400,
  7418.                 ])), 400);
  7419.             }
  7420.             /** @var AudioCentre */
  7421.             $liaison $this->getDoctrine()
  7422.                 ->getRepository(AudioCentre::class)
  7423.                 ->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
  7424.             if ($liaison == null) {
  7425.                 return new Response(json_encode(([
  7426.                     'message' => 'Error, audio isnt part of the centre',
  7427.                     'path' => 'src/Controller/RdvController.php',
  7428.                     "status" => 400,
  7429.                 ])), 400);
  7430.             }
  7431.             $rdv->setIdCentre($centre);
  7432.         } elseif (isset($data["lieu_id"]) && $audio->getIsIndie()) {
  7433.             // tries to set the lieu if it's an audio indie
  7434.             $lieu $this->getDoctrine()
  7435.                 ->getRepository(Lieu::class)
  7436.                 ->findOneBy(['id' => $data["lieu_id"], 'id_gerant' => $data["audio_id"]]);
  7437.             if ($lieu == null) {
  7438.                 return new Response(json_encode(([
  7439.                     'message' => 'Error, no lieu found at this id',
  7440.                     'path' => 'src/Controller/RdvController.php',
  7441.                     "status" => 400,
  7442.                 ])), 400);
  7443.             }
  7444.             $rdv->setIdLieu($lieu);
  7445.         } else {
  7446.             return new Response(json_encode(([
  7447.                 'message' => 'Error, no lieu/centre id',
  7448.                 'path' => 'src/Controller/RdvController.php',
  7449.                 "status" => 400,
  7450.             ])), 400);
  7451.         }
  7452.         /** @var Motif */
  7453.         $motif $this->getDoctrine()
  7454.             ->getRepository(Motif::class)
  7455.             ->find($data["motif_id"]);
  7456.         if ($motif == null) {
  7457.             return new Response(json_encode(([
  7458.                 'message' => 'Error, no motif found at this id',
  7459.                 'path' => 'src/Controller/RdvController.php',
  7460.                 "status" => 400,
  7461.             ])), 400);
  7462.         }
  7463.         /** @var AudioMotif */
  7464.         $audioMotif $this->getDoctrine()
  7465.             ->getRepository(AudioMotif::class)
  7466.             ->findOneBy(["id_audio" => $audio->getId(), "id_motif" => $data["motif_id"]]);
  7467.         if ($audioMotif == null) {
  7468.             return new Response(json_encode(([
  7469.                 'message' => 'Error, no motif of this id found at this audio',
  7470.                 'path' => 'src/Controller/RdvController.php',
  7471.                 "status" => 400,
  7472.             ])), 400);
  7473.         }
  7474.         // remove the taken schedule by rdv to make sure there is no overlap
  7475.         $data["date"] = str_replace("h"":"$data["date"]);
  7476.         $date \DateTime::createFromFormat("Y-m-d\TH:i"$data["date"]);
  7477.         if (isset($data["note"])) {
  7478.             $rdv->setNote($data["note"]);
  7479.         }
  7480.         $date \DateTime::createFromFormat("Y-m-d\TH:i"$data["date"]);
  7481.         $rdv->setDate($date);
  7482.         $rdv->setDateCreation(\DateTime::createFromFormat("d/m/Y H:i"date('d/m/Y H:i')));
  7483.         /** @var EtatRdv */
  7484.         $etat $this->getDoctrine()
  7485.             ->getRepository(EtatRdv::class)
  7486.             ->findOneBy(['id' => $data["etat_id"]]);
  7487.         if ($etat == null) {
  7488.             return new Response(json_encode(([
  7489.                 'message' => 'Error, no etat found at this id',
  7490.                 'path' => 'src/Controller/RdvController.php',
  7491.                 "status" => 400,
  7492.             ])), 400);
  7493.         }
  7494.         $rdv->setIdEtat($etat);
  7495.         $rdv->setIdMotif($motif);
  7496.         $rdv->setIsAbsence(0);
  7497.         $rdv->setCacher(0);
  7498.         $entityManager $this->getDoctrine()->getManager();
  7499.         $entityManager->persist($rdv);
  7500.         $leadRdv->setRdv($rdv);
  7501.         $leadStatus $this->entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'rdv_valider']);
  7502.         $leadRdv->setLeadStatus($leadStatus);
  7503.         $entityManager->flush();
  7504.         /// SMSEMAIL A décommenter pour autoriser l'envoi de sms / email à la création de rdv par l'audio / le client SMSEMAIL ///
  7505.         $date $rdv->getDate();
  7506.         $smsDate $date->format('d-m-Y H:i');
  7507.         $locale 'fr_FR';
  7508.         $formatter = new IntlDateFormatter(
  7509.             $locale,
  7510.             IntlDateFormatter::FULL,
  7511.             IntlDateFormatter::SHORT,
  7512.             null,
  7513.             IntlDateFormatter::GREGORIAN,
  7514.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  7515.         );
  7516.         $smsDateLongFormat $formatter->format($date);
  7517.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  7518.         $client->setIdCentre($rdv->getIdCentre());
  7519.         $client->setIdAudio($rdv->getIdAudio());
  7520.         $entityManager->persist($client);
  7521.         $entityManager->flush();
  7522.         // client notif mail Sms
  7523.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  7524.         $frenchDate ucfirst($frenchDate);
  7525.         $params = array(
  7526.             "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  7527.             "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  7528.             "date" => $smsDateLongFormat,
  7529.             "RdvDate" => $smsDateLongFormat,
  7530.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  7531.             "centerName" => $rdv->getIdCentre()->getName(),
  7532.             "prenom" => $client->getName(),
  7533.             "centerAddress" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  7534.             "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  7535.             'motif' => $rdv->getIdMotif()->getTitre(),
  7536.             "centerCity" => $rdv->getIdCentre()->getCity(),
  7537.             "audioName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  7538.             'titre' => "Votre rendez-vous est validé le " substr($smsDate010) . " à "  substr($smsDate1115),
  7539.             "position" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  7540.             "address" => $rdv->getIdCentre()->getAddress(),
  7541.             "postal" => $rdv->getIdCentre()->getPostale(),
  7542.             "city" => $rdv->getIdCentre()->getCity(),
  7543.             "clientEmail" => $client->getMail(),
  7544.             "clientPassword" => isset($data["passwordGenerated"]) ? $data["passwordGenerated"] : null,
  7545.             "clientAddress" => $client->getAddress(),
  7546.             "clientPostal" => $client->getPostal(),
  7547.             "clientCity" => $client->getCity(),
  7548.             "audioName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  7549.             "frenchDate" => $frenchDate,
  7550.             "heure" => substr($smsDate1115),
  7551.             "centerName" => $rdv->getIdCentre()->getName(),
  7552.             "audioMail" => $rdv->getIdAudio()->getMail(),
  7553.             "modifUrl" => "{$_ENV['BASE_client']}mes-rendez-vous",
  7554.         );
  7555.         $paramsPatient $params;
  7556.         $isNew false;
  7557.         if (isset($data["isLead"]) && isset($data["passwordGenerated"]) != null) {
  7558.             $subject "✅Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  7559.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject189);
  7560.             $isNew true;
  7561.         } else {
  7562.             $subject "Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  7563.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject181);
  7564.         }
  7565.         $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.";
  7566.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  7567.         // audio Notif mail SMS
  7568.         $birthday $rdv->getIdClient()->getBirthdate();
  7569.         $params = array(
  7570.             "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  7571.             "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  7572.             "date" => substr($smsDate010),
  7573.             "heure" => substr($smsDate1115),
  7574.             "mail" => $client->getMail(),
  7575.             "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  7576.             'telClient' => $client->getPhone(),
  7577.             'phone' => $client->getPhone(),
  7578.             'clientCivilite' => $client->getCivilite(),
  7579.             'clientNom' => $client->getLastname(),
  7580.             'clientPrenom' => $client->getName(),
  7581.             'clientPostal' => $client->getPostal(),
  7582.             'clientMail' => $client->getMail(),
  7583.             'clientPhone' => $client->getPhone(),
  7584.             'motif' => $rdv->getIdMotif()->getTitre(),
  7585.             'birthdate' => $client->getBirthdate() ? $client->getBirthdate()->format("d/m/Y") : null,
  7586.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  7587.             'centerName' => $rdv->getIdCentre()->getName(),
  7588.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  7589.             'centerCity' => $rdv->getIdCentre()->getCity(),
  7590.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  7591.             'idPatient' => $client->getId(),
  7592.             'proUrl' => "{$_ENV['BASE_logiciel']}",
  7593.             'frenchDate' => $frenchDate,
  7594.             'responses' => $responses,
  7595.         );
  7596.         $templateEmail 182;
  7597.         if (!empty($data['canMove'])) {
  7598.             $templateEmail 197;
  7599.         }
  7600.         $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  7601.         $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  7602.         if ($rdv->getIdAudio()->getConfirmRdvMail()) {
  7603.             $subject "✅ Nouveau Rendez-vous My Audio le " $frenchDate " à " substr($smsDate1115);
  7604.             $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject$templateEmail);
  7605.         }
  7606.         if ($rdv->getIdAudio()->getConfirmRdvSms()) {
  7607.             $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.";
  7608.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  7609.         }
  7610.         $age null;
  7611.         if ($client->getBirthdate()) {
  7612.             $age $client->getBirthdate()->diff(new \DateTime())->y;
  7613.         }
  7614.         // Génère le PDF à partir d’un template
  7615.         $pdfContent $this->generatePdf(
  7616.             'pdf/rdv_recap.html.twig',
  7617.             [
  7618.                 'id' => $client->getId() ?? '',
  7619.                 'nom' => $client->getName() ?? '',
  7620.                 'prenom' => $client->getLastname() ?? '',
  7621.                 'birthday' =>  $client->getBirthdate() ? $client->getBirthdate()->format("d/m/Y") : null,
  7622.                 'age' => $age,
  7623.                 'adresse' => $client->getAddress() ?? '',
  7624.                 'postal' => $client->getPostal() ?? '',
  7625.                 'city' => $client->getCity() ?? '',
  7626.                 'phone' => $client->getPhone() ?? '',
  7627.                 'mail' => $client->getMail() ?? '',
  7628.                 'centerName' => $rdv->getIdCentre()->getName() ?? '',
  7629.                 "date" => substr($smsDate010) ?? '',
  7630.                 "heure" => substr($smsDate1115) ?? '',
  7631.                 'duration' => $rdv->getDuration(),
  7632.                 "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  7633.                 'motif' => $rdv->getIdMotif() ? $rdv->getIdMotif()->getTitre() : '',
  7634.                 'situations' => $this->formatImploded($leadRdv->getSituationsGene()),
  7635.                 'IntensiteGen' => $leadRdv->getIntensiteGene() ?? '',
  7636.                 'devicePref' => $this->formatImploded($leadRdv->getPreferenceDevice()),
  7637.                 'deviceModelPref' =>  implode(", "$leadRdv->getDeviceModelPreference()),
  7638.                 'criterePrincipal' => $this->formatImploded($leadRdv->getCriterePrincipal()),
  7639.                 'accoupheneCote' =>  $leadRdv->getAcoupheneCote() ?? '',
  7640.                 'originePerte' => $this->formatImploded($leadRdv->getOriginePerte()),
  7641.                 'diabete' =>  $leadRdv->getDiabete() ?? '',
  7642.                 'hypertension' =>  $leadRdv->getHypertension() ?? '',
  7643.                 'mutuelle' =>  $leadRdv->getMutuelle() ?? '',
  7644.                 'nameMutuelle' =>  $leadRdv->getNameMutuelle() ?? '',
  7645.                 'priseEnCharge' => $leadRdv->getPriseEnCharge() ?? '',
  7646.                 'budget' => $leadRdv->getBudget() ?? '',
  7647.                 'equipeAppareil' => $leadRdv->getEquipeAppareil() ?? '',
  7648.                 'durationEquipe' => $leadRdv->getDurationEquipeAppareil() ?? '',
  7649.                 'bilanAuditif' => $leadRdv->getBilanAuditif() ?? '',
  7650.                 'ordonance' => $leadRdv->getOrdonance() ?? '',
  7651.                 'dateOrdonance' => $leadRdv->getDateOrdonance() ?? '',
  7652.                 'canMove' => $leadRdv->getCanMove() ?? '',
  7653.                 'comment' => $leadRdv->getComment() ?? '',
  7654.             ],
  7655.             $this->getParameter('kernel.project_dir') . '/public/assets/pdf/recap-rdv-myaudio.pdf'
  7656.         );
  7657.         $this->sendEmailWithPdfAttachmentThenDelete(
  7658.             $params,
  7659.             $mailAudio,
  7660.             $client->getName(),
  7661.             $subject,
  7662.             $templateEmail// ID du template Sendinblue
  7663.             $pdfContent
  7664.         );
  7665.         // send notif to admin
  7666.         $paramsSourceLead = [
  7667.             'trafficSource' => "EasyAdmin",
  7668.         ];
  7669.         $paramsAdmin = array(
  7670.             "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  7671.             "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  7672.             "RdvDate" => substr($smsDate010),
  7673.             "heure" => substr($smsDate1115),
  7674.             "clientMail" => $client->getMail(),
  7675.             "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  7676.             'telClient' => $client->getPhone(),
  7677.             'clientNom' => $client->getLastname(),
  7678.             'clientPrenom' => $client->getName(),
  7679.             'clientCivilite' => $client->getCivilite(),
  7680.             'clientPostal' => $client->getPostal(),
  7681.             'clientPhone' => $client->getPhone(),
  7682.             'motif' => $rdv->getIdMotif()->getTitre(),
  7683.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  7684.             'centerName' => $rdv->getIdCentre()->getName(),
  7685.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  7686.             'centerCity' => $rdv->getIdCentre()->getCity(),
  7687.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  7688.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  7689.             'date' => substr($smsDate010),
  7690.             'urlApi' => "{$_ENV['BASE_API']}",
  7691.             'clientId' => $client->getId(),
  7692.             'centerId' => $rdv->getIdCentre()->getId(),
  7693.             'frenchDate' => $frenchDate,
  7694.             'responses' => $responses,
  7695.             'paramsSourceLead' => $paramsSourceLead
  7696.         );
  7697.         $subject "Nouveau RDV MA | RR - " $rdv->getIdCentre()->getName();
  7698.         $templateEmail 183;
  7699.         if (!empty($data['canMove'])) {
  7700.             $templateEmail 190;
  7701.         }
  7702.         $publicFunction->sendEmail($paramsAdmin"contact@myaudio.fr""my audio"$subject$templateEmail);
  7703.         $publicFunction->sendEmail($paramsAdmin"lead.myaudio@gmail.com""my audio"$subject$templateEmail);
  7704.         $specificSubscription $this->getDoctrine()
  7705.              ->getRepository(SpecificSubscription::class)
  7706.              ->findOneBy(['audio' => $audio]);
  7707.       if ($specificSubscription && $specificSubscription->getContractCategory()) {
  7708.         $contractCategory $specificSubscription->getContractCategory();
  7709.       if ($contractCategory->getName() === "OPTICAL CENTER SUCCURSALE") {
  7710.         $publicFunction->sendEmail($paramsAdmin"christel.montagne@optical-center.com""my audio"$subject246);
  7711.          }
  7712.        }
  7713.         try {
  7714.             $Callservice->handleCallCenterAfterRdv(
  7715.                 $rdv
  7716.             );
  7717.             $rdv->setIsNotificationRdvCallSent(1);
  7718.             $this->entityManager->flush();
  7719.         } catch (\Exception $e) {
  7720.             $this->logger->error("Erreur lors de l'appel de notification pour le RDV #{$rdv->getId()}: " $e->getMessage());
  7721.         }
  7722.         // google calendar post
  7723.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  7724.             ->findBy(array('audio' => $audio->getId()));
  7725.         $data['rdv'] = $rdv->getId();
  7726.         foreach ($synchronisations as $synchronisation) {
  7727.             if (!$synchronisation->getIsDeleted()) {
  7728.                 $googleCalendar->checkAndRefreshAccessToken($synchronisation);
  7729.                 $googleCalendar->createEvent($synchronisation$data);
  7730.             }
  7731.         }
  7732.         return new Response(json_encode(([
  7733.             "id" => $rdv->getId(),
  7734.             "motif_id" => $rdv->getIdMotif()->getId(),
  7735.             "audio_id" => $rdv->getIdAudio()->getId(),
  7736.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  7737.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  7738.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  7739.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  7740.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  7741.             "testclient" => $rdv->getTestClient() ? [
  7742.                 "result" => $rdv->getTestClient()->getResultTonal(),
  7743.                 "date" => $rdv->getTestClient()->getDate(),
  7744.                 "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  7745.             ] : null,
  7746.             "duration" => $audioMotif->getDuration(),
  7747.             "consigne" => $audioMotif->getConsigne(),
  7748.             "etat_id" => $rdv->getIdEtat()->getId(),
  7749.             "date" => $rdv->getDate(),
  7750.             "comment" => $rdv->getComment(),
  7751.             "centerName" => $rdv->getIdCentre()->getName(),
  7752.             "review" => $rdv->getReview(),
  7753.             "note" => $rdv->getNote(),
  7754.             "status" => 200,
  7755.             "paramsPatient" => $paramsPatient,
  7756.             "isNew" => $isNew,
  7757.         ])));
  7758.     }
  7759.     private function generatePdf(string $template, array $data = [], string $outputPath): string
  7760.     {
  7761.         // Render le contenu HTML avec Twig
  7762.         $html $this->twig->render($template$data);
  7763.         // Configurer Dompdf
  7764.         $options = new Options();
  7765.         $options->set('defaultFont''Arial');
  7766.         $dompdf = new Dompdf($options);
  7767.         $dompdf->loadHtml($html);
  7768.         $dompdf->setPaper('A4''portrait');
  7769.         $dompdf->render();
  7770.         // Sauvegarder le PDF
  7771.         file_put_contents($outputPath$dompdf->output());
  7772.         return $outputPath// Renvoie le chemin du fichier PDF généré
  7773.     }
  7774.     private function sendEmailWithPdfAttachmentThenDelete(
  7775.         array $params,
  7776.         string $mail,
  7777.         string $name,
  7778.         string $subject,
  7779.         int $templateId,
  7780.         string $pdfFilePath
  7781.     ): void {
  7782.         // Lire et encoder le contenu du PDF
  7783.         $attachment = [
  7784.             "name" => basename($pdfFilePath),
  7785.             "content" => base64_encode(file_get_contents($pdfFilePath)),
  7786.         ];
  7787.         // Construire les données pour l’API Sendinblue
  7788.         $data = [
  7789.             "sender" => [
  7790.                 "email" => 'noreply@myaudio.fr',
  7791.                 "name" => 'My Audio',
  7792.             ],
  7793.             "to" => [
  7794.                 [
  7795.                     "email" => $mail,
  7796.                     "name" => $name,
  7797.                 ],
  7798.             ],
  7799.             "subject" => $subject,
  7800.             "templateId" => $templateId,
  7801.             "params" => $params,
  7802.             "attachment" => [$attachment],
  7803.         ];
  7804.         // Envoi via cURL
  7805.         $ch curl_init();
  7806.         curl_setopt($chCURLOPT_URL'https://api.sendinblue.com/v3/smtp/email');
  7807.         curl_setopt($chCURLOPT_RETURNTRANSFER1);
  7808.         curl_setopt($chCURLOPT_POST1);
  7809.         curl_setopt($chCURLOPT_POSTFIELDSjson_encode($data));
  7810.         $headers = [
  7811.             'Accept: application/json',
  7812.             'Api-Key: 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',
  7813.             'Content-Type: application/json',
  7814.         ];
  7815.         curl_setopt($chCURLOPT_HTTPHEADER$headers);
  7816.         $result curl_exec($ch);
  7817.         if (curl_errno($ch)) {
  7818.             echo 'Erreur email : ' curl_error($ch);
  7819.         }
  7820.         curl_close($ch);
  7821.         // Supprimer le PDF après envoi
  7822.         if (file_exists($pdfFilePath)) {
  7823.             unlink($pdfFilePath);
  7824.         }
  7825.     }
  7826.     private function formatImploded(array $data): string
  7827.     {
  7828.         return implode(', 'array_map(function ($item) {
  7829.             return str_replace('_'' '$item);
  7830.         }, $data));
  7831.     }
  7832.     /**
  7833.      * 
  7834.      * @Route("/admin/rdv/export-pdf-form", name="admin_rdv_export_pdf_form", methods={"GET", "POST"})
  7835.      */
  7836.     public function exportPdfForm(Request $request): Response
  7837.     {
  7838.         $form $this->createFormBuilder()
  7839.             ->add('startDate'\Symfony\Component\Form\Extension\Core\Type\DateType::class, [
  7840.                 'label' => 'Date de début',
  7841.                 'widget' => 'single_text',
  7842.                 'html5' => true,
  7843.                 'required' => true,
  7844.             ])
  7845.             ->add('endDate'\Symfony\Component\Form\Extension\Core\Type\DateType::class, [
  7846.                 'label' => 'Date de fin',
  7847.                 'widget' => 'single_text',
  7848.                 'html5' => true,
  7849.                 'required' => true,
  7850.             ])
  7851.             ->add('format'\Symfony\Component\Form\Extension\Core\Type\ChoiceType::class, [
  7852.                 'label' => 'Format d\'export',
  7853.                 'choices' => [
  7854.                     'PDF' => 'pdf',
  7855.                     'Excel' => 'excel',
  7856.                 ],
  7857.                 'expanded' => false,
  7858.                 'multiple' => false,
  7859.                 'required' => true,
  7860.             ])
  7861.             ->getForm();
  7862.         //dd($request);
  7863.         $form->handleRequest($request);
  7864.         if ($form->isSubmitted() && $form->isValid()) {
  7865.             $data $form->getData();
  7866.             $start $data['startDate']->format('Y-m-d');
  7867.             $end $data['endDate']->format('Y-m-d');
  7868.             if ($data['format'] === 'pdf') {
  7869.                 return $this->redirectToRoute('admin_rdv_export_pdf', [
  7870.                     'startDate' => $start,
  7871.                     'endDate' => $end,
  7872.                 ]);
  7873.             } else {
  7874.                 return $this->redirectToRoute('admin_rdv_export_excel', [
  7875.                     'startDate' => $start,
  7876.                     'endDate' => $end,
  7877.                 ]);
  7878.             }
  7879.         }
  7880.         return $this->render('easyadmin/rdv/export_pdf_form.html.twig', [
  7881.             'form' => $form->createView(),
  7882.         ]);
  7883.     }
  7884.     /**
  7885.      * 
  7886.      * @Route("/optical/rdv/export-pdf-form", name="optical_rdv_export_pdf_form", methods={"GET", "POST"})
  7887.      */
  7888.     public function exportOpticalPdfForm(Request $request): Response
  7889.     {
  7890.         $form $this->createFormBuilder()
  7891.             ->add('startDate'\Symfony\Component\Form\Extension\Core\Type\DateType::class, [
  7892.                 'label' => 'Date de début',
  7893.                 'widget' => 'single_text',
  7894.                 'html5' => true,
  7895.                 'required' => true,
  7896.             ])
  7897.             ->add('endDate'\Symfony\Component\Form\Extension\Core\Type\DateType::class, [
  7898.                 'label' => 'Date de fin',
  7899.                 'widget' => 'single_text',
  7900.                 'html5' => true,
  7901.                 'required' => true,
  7902.             ])
  7903.             ->add('format'\Symfony\Component\Form\Extension\Core\Type\ChoiceType::class, [
  7904.                 'label' => 'Format d\'export',
  7905.                 'choices' => [
  7906.                     'PDF' => 'pdf',
  7907.                     'Excel' => 'excel',
  7908.                 ],
  7909.                 'expanded' => false,
  7910.                 'multiple' => false,
  7911.                 'required' => true,
  7912.             ])
  7913.             ->getForm();
  7914.         //dd($request);
  7915.         $form->handleRequest($request);
  7916.         if ($form->isSubmitted() && $form->isValid()) {
  7917.             $data $form->getData();
  7918.             $start $data['startDate']->format('Y-m-d');
  7919.             $end $data['endDate']->format('Y-m-d');
  7920.             if ($data['format'] === 'pdf') {
  7921.                 return $this->redirectToRoute('optical_rdv_export_pdf', [
  7922.                     'startDate' => $start,
  7923.                     'endDate' => $end,
  7924.                 ]);
  7925.             } else {
  7926.                 return $this->redirectToRoute('optical_rdv_export_excel', [
  7927.                     'startDate' => $start,
  7928.                     'endDate' => $end,
  7929.                 ]);
  7930.             }
  7931.         }
  7932.         return $this->render('easyadmin/rdv/export_pdf_form.html.twig', [
  7933.             'form' => $form->createView(),
  7934.         ]);
  7935.     }
  7936.     /**
  7937.      * @Route("/admin/lead-rdv/update-status", name="admin_lead_rdv_update_status", methods={"POST"})
  7938.      */
  7939.     public function updateStatus(Request $request): JsonResponse
  7940.     {
  7941.         // Récupérer les données envoyées en AJAX
  7942.         $data json_decode($request->getContent(), true);
  7943.         $leadId $data['leadId'] ?? null;
  7944.         $statusId $data['statusId'] ?? null;
  7945.         if (!$leadId || !$statusId) {
  7946.             return new JsonResponse(['success' => false'message' => 'Données manquantes'], 400);
  7947.         }
  7948.         // Récupérer le lead et le statut
  7949.         $lead $this->entityManager->getRepository(LeadRdv::class)->find($leadId);
  7950.         $status $this->entityManager->getRepository(LeadStatus::class)->find($statusId);
  7951.         if (!$lead || !$status) {
  7952.             return new JsonResponse(['success' => false'message' => 'Lead ou statut introuvable'], 404);
  7953.         }
  7954.         // Mettre à jour le statut du lead
  7955.         $lead->setLeadStatus($status);
  7956.         $this->entityManager->flush();
  7957.         return new JsonResponse(['success' => true]);
  7958.     }
  7959.     /**
  7960.      * @Route("/admin/rdv/update-client-status", name="admin_rdv_update_client_status", methods={"POST"})
  7961.      */
  7962.     public function updateClientStatus(Request $request): JsonResponse
  7963.     {
  7964.         $data json_decode($request->getContent(), true);
  7965.         $rdvId $data['rdvId'] ?? null;
  7966.         $statusId $data['statusId'] ?? null;
  7967.         if (!$rdvId || !$statusId) {
  7968.             return new JsonResponse(['success' => false'message' => 'Données manquantes'], 400);
  7969.         }
  7970.         // Récupérer le RDV
  7971.         $rdv $this->entityManager->getRepository(Rdv::class)->find($rdvId);
  7972.         if (!$rdv) {
  7973.             return new JsonResponse(['success' => false'message' => 'RDV non trouvé'], 404);
  7974.         }
  7975.         // Récupérer le statut
  7976.         $clientStatus $this->entityManager->getRepository(ClientStatus::class)->find($statusId);
  7977.         if (!$clientStatus) {
  7978.             return new JsonResponse(['success' => false'message' => 'Statut non trouvé'], 404);
  7979.         }
  7980.         // Mettre à jour le client
  7981.         $client $rdv->getIdClient();
  7982.         if ($client) {
  7983.             $client->setClientStatus($clientStatus);
  7984.             $this->entityManager->flush();
  7985.             // Si le statut est "Facturé", lancer la facturation
  7986.             if ((int)$statusId === 2) {
  7987.                 // Réutiliser la méthode de facturation existante
  7988.                 $crudController $this->container->get(RdvMyAudioCrudController::class);
  7989.                 $crudController->billing($rdv);
  7990.             }
  7991.             return new JsonResponse(['success' => true]);
  7992.         }
  7993.         return new JsonResponse(['success' => false'message' => 'Client non trouvé'], 404);
  7994.     }
  7995.     /**
  7996.      * @Route("/admin/rdv/update-rdv-status", name="admin_rdv_update_status", methods={"POST"})
  7997.      */
  7998.     public function updateRdvStatus(Request $requestEntityManagerInterface $entityManager): JsonResponse
  7999.     {
  8000.         $data json_decode($request->getContent(), true);
  8001.         $rdvId $data['rdvId'] ?? null;
  8002.         $statusId $data['statusId'] ?? null;
  8003.         if (!$rdvId || !$statusId) {
  8004.             return new JsonResponse(['success' => false'message' => 'Données manquantes'], 400);
  8005.         }
  8006.         // Récupérer le RDV
  8007.         $rdv $entityManager->getRepository(Rdv::class)->find($rdvId);
  8008.         if (!$rdv) {
  8009.             return new JsonResponse(['success' => false'message' => 'RDV non trouvé'], 404);
  8010.         }
  8011.         // Récupérer le statut
  8012.         $etatRdv $entityManager->getRepository(EtatRdv::class)->find($statusId);
  8013.         if (!$etatRdv) {
  8014.             return new JsonResponse(['success' => false'message' => 'Statut non trouvé'], 404);
  8015.         }
  8016.         // Mettre à jour le statut du RDV
  8017.         $rdv->setIdEtat($etatRdv);
  8018.         $entityManager->flush();
  8019.         return new JsonResponse(['success' => true]);
  8020.     }
  8021.     /**
  8022.      * @Route("/admin/rdv/export-pdf/{startDate}/{endDate}", name="admin_rdv_export_pdf", methods={"GET"})
  8023.      */
  8024.     public function exportPdfFromDate(string $startDatestring $endDateKernelInterface $kernel): Response
  8025.     {
  8026.         $start = new \DateTimeImmutable($startDate);
  8027.         $end = new \DateTimeImmutable($endDate);
  8028.         $today = new \DateTimeImmutable();
  8029.         $rdvs $this->rdvRepository->findBySinceDateAndMyAudio($start$end);
  8030.         $html "
  8031.     <html>
  8032.     <head>
  8033.         <style>
  8034.             body { font-family: Arial, sans-serif; font-size: 13px; }
  8035.             table { width: 100%; border-collapse: collapse; font-size: 11px; }
  8036.             th, td { border: 1px solid #000; padding: 5px; text-align: left; }
  8037.             th { font-weight: bold; }
  8038.             h1 { font-size: 14px; }
  8039.         </style>
  8040.     </head>
  8041.     <body>
  8042.         <h1>Rendez-vous My Audio du " $start->format('d/m/Y') . " au " $end->format('d/m/Y') . "</h1>
  8043.         <table cellspacing='0' cellpadding='5'>
  8044.             <thead>
  8045.                 <tr>
  8046.                     <th>ID du RDV</th>
  8047.                     <th>Date du RDV</th>
  8048.                     <th>Jours écoulés</th>
  8049.                     <th>Statut RDV</th>
  8050.                     <th>Nom patient</th>
  8051.                     <th>Téléphone patient</th>
  8052.                     <th>Statut patient</th>
  8053.                     <th>Centre</th>
  8054.                     <th>Téléphone Centre</th>
  8055.                     <th>Adresse</th>
  8056.                     <th>Nom Audio</th>
  8057.                 </tr>
  8058.             </thead>
  8059.             <tbody>";
  8060.         foreach ($rdvs as $rdv) {
  8061.             $dateRdv $rdv->getDate();
  8062.             $joursEcoules $dateRdv->diff($today)->days;
  8063.             $client $rdv->getIdClient();
  8064.             $centre $rdv->getIdCentre();
  8065.             $etat $rdv->getIdEtat();
  8066.             $audio $rdv->getIdAudio();
  8067.             $html .= "<tr>
  8068.             <td>" $rdv->getId() . "</td>
  8069.             <td>" $dateRdv->format('d/m/Y H:i') . "</td>
  8070.             <td>" $joursEcoules " jours</td>
  8071.             <td>" . ($etat htmlspecialchars($etat->getLibelle()) : 'Non défini') . "</td>
  8072.             <td>" . ($client htmlspecialchars($client->getName() . ' ' $client->getLastname()) : '') . "</td>
  8073.             <td>" . ($client htmlspecialchars($client->getPhone()) : '') . "</td>
  8074.             <td>" . ($client && $client->getClientStatus() ? htmlspecialchars($client->getClientStatus()->getLibelle()) : 'Non défini') . "</td>
  8075.             <td>" . ($centre htmlspecialchars($centre->getName()) : '') . "</td>
  8076.             <td>" . ($centre htmlspecialchars($centre->getPhone()) : '') . "</td>
  8077.             <td>" . ($centre htmlspecialchars($centre->getAddress() . ', ' $centre->getPostale() . ' ' $centre->getCity()) : '') . "</td>
  8078.             <td>" . ($audio htmlspecialchars($audio->getCivilite() . ' ' $audio->getName() . ' ' $audio->getLastname()) : '') . "</td>
  8079.         </tr>";
  8080.         }
  8081.         $html .= "</tbody></table></body></html>";
  8082.         // Configuration et rendu du PDF
  8083.         $options = new Options();
  8084.         $options->set('defaultFont''Arial');
  8085.         $dompdf = new Dompdf($options);
  8086.         $dompdf->loadHtml($html);
  8087.         $dompdf->setPaper('A4''landscape');
  8088.         $dompdf->render();
  8089.         // Création du dossier s'il n'existe pas
  8090.         $projectDir $kernel->getProjectDir();
  8091.         $outputDir $projectDir '/public/assets/pdf/rdv';
  8092.         $filesystem = new Filesystem();
  8093.         if (!$filesystem->exists($outputDir)) {
  8094.             $filesystem->mkdir($outputDir0775);
  8095.         }
  8096.         $filenameDate $start->format('Y-m-d') . '_to_' $end->format('Y-m-d');
  8097.         $outputPath "$outputDir/rdvs-$filenameDate.pdf";
  8098.         file_put_contents($outputPath$dompdf->output());
  8099.         return new Response($dompdf->output(), 200, [
  8100.             'Content-Type' => 'application/pdf',
  8101.             'Content-Disposition' => 'attachment; filename="rdvs-' $filenameDate '.pdf"',
  8102.         ]);
  8103.     }
  8104.     /**
  8105.      * @Route("/optical/rdv/export-pdf/{startDate}/{endDate}", name="optical_rdv_export_pdf", methods={"GET"})
  8106.      */
  8107.     public function exportOpticalPdfFromDate(string $startDatestring $endDateKernelInterface $kernel): Response
  8108.     {
  8109.         $start = new \DateTimeImmutable($startDate);
  8110.         $end = new \DateTimeImmutable($endDate);
  8111.         $today = new \DateTimeImmutable();
  8112.         $rdvs $this->rdvRepository->findOpticalBySinceDateAndMyAudio($start$end);
  8113.         $html "
  8114.     <html>
  8115.     <head>
  8116.         <style>
  8117.             body { font-family: Arial, sans-serif; font-size: 13px; }
  8118.             table { width: 100%; border-collapse: collapse; font-size: 11px; }
  8119.             th, td { border: 1px solid #000; padding: 5px; text-align: left; }
  8120.             th { font-weight: bold; }
  8121.             h1 { font-size: 14px; }
  8122.         </style>
  8123.     </head>
  8124.     <body>
  8125.         <h1>Rendez-vous My Audio du " $start->format('d/m/Y') . " au " $end->format('d/m/Y') . "</h1>
  8126.         <table cellspacing='0' cellpadding='5'>
  8127.             <thead>
  8128.                 <tr>
  8129.                     <th>ID du RDV</th>
  8130.                     <th>Date du RDV</th>
  8131.                     <th>Jours écoulés</th>
  8132.                     <th>Statut RDV</th>
  8133.                     <th>Nom patient</th>
  8134.                     <th>Téléphone patient</th>
  8135.                     <th>Statut patient</th>
  8136.                     <th>Centre</th>
  8137.                     <th>Téléphone Centre</th>
  8138.                     <th>Adresse</th>
  8139.                     <th>Nom Audio</th>
  8140.                 </tr>
  8141.             </thead>
  8142.             <tbody>";
  8143.         foreach ($rdvs as $rdv) {
  8144.             $dateRdv $rdv->getDate();
  8145.             $joursEcoules $dateRdv->diff($today)->days;
  8146.             $client $rdv->getIdClient();
  8147.             $centre $rdv->getIdCentre();
  8148.             $etat $rdv->getIdEtat();
  8149.             $audio $rdv->getIdAudio();
  8150.             $html .= "<tr>
  8151.             <td>" $rdv->getId() . "</td>
  8152.             <td>" $dateRdv->format('d/m/Y H:i') . "</td>
  8153.             <td>" $joursEcoules " jours</td>
  8154.             <td>" . ($etat htmlspecialchars($etat->getLibelle()) : 'Non défini') . "</td>
  8155.             <td>" . ($client htmlspecialchars($client->getName() . ' ' $client->getLastname()) : '') . "</td>
  8156.             <td>" . ($client htmlspecialchars($client->getPhone()) : '') . "</td>
  8157.             <td>" . ($client && $client->getClientStatus() ? htmlspecialchars($client->getClientStatus()->getLibelle()) : 'Non défini') . "</td>
  8158.             <td>" . ($centre htmlspecialchars($centre->getName()) : '') . "</td>
  8159.             <td>" . ($centre htmlspecialchars($centre->getPhone()) : '') . "</td>
  8160.             <td>" . ($centre htmlspecialchars($centre->getAddress() . ', ' $centre->getPostale() . ' ' $centre->getCity()) : '') . "</td>
  8161.             <td>" . ($audio htmlspecialchars($audio->getCivilite() . ' ' $audio->getName() . ' ' $audio->getLastname()) : '') . "</td>
  8162.         </tr>";
  8163.         }
  8164.         $html .= "</tbody></table></body></html>";
  8165.         // Configuration et rendu du PDF
  8166.         $options = new Options();
  8167.         $options->set('defaultFont''Arial');
  8168.         $dompdf = new Dompdf($options);
  8169.         $dompdf->loadHtml($html);
  8170.         $dompdf->setPaper('A4''landscape');
  8171.         $dompdf->render();
  8172.         // Création du dossier s'il n'existe pas
  8173.         $projectDir $kernel->getProjectDir();
  8174.         $outputDir $projectDir '/public/assets/pdf/rdv';
  8175.         $filesystem = new Filesystem();
  8176.         if (!$filesystem->exists($outputDir)) {
  8177.             $filesystem->mkdir($outputDir0775);
  8178.         }
  8179.         $filenameDate $start->format('Y-m-d') . '_to_' $end->format('Y-m-d');
  8180.         $outputPath "$outputDir/rdvs-$filenameDate.pdf";
  8181.         file_put_contents($outputPath$dompdf->output());
  8182.         return new Response($dompdf->output(), 200, [
  8183.             'Content-Type' => 'application/pdf',
  8184.             'Content-Disposition' => 'attachment; filename="rdvs-' $filenameDate '.pdf"',
  8185.         ]);
  8186.     }
  8187.     /**
  8188.      * 
  8189.      * @Route("/admin/rdv/export/excel/{startDate}/{endDate}", name="admin_rdv_export_excel", methods={"GET"})
  8190.      */
  8191.     public function exportExcelFromDate(string $startDatestring $endDate): Response
  8192.     {
  8193.         $start = new \DateTimeImmutable($startDate);
  8194.         $end = new \DateTimeImmutable($endDate);
  8195.         $rdvs $this->rdvRepository->findBySinceDateAndMyAudio($start$end);
  8196.         $spreadsheet = new Spreadsheet();
  8197.         $sheet $spreadsheet->getActiveSheet();
  8198.         // Headers
  8199.         $sheet->fromArray([
  8200.             'ID du RDV',
  8201.             'Date du RDV',
  8202.             'Jours écoulés',
  8203.             'Statut RDV',
  8204.             'Nom patient',
  8205.             'Téléphone patient',
  8206.             'Statut patient',
  8207.             'Centre',
  8208.             'Téléphone Centre',
  8209.             'Adresse',
  8210.             'Nom Audio'
  8211.         ], null'A1');
  8212.         $today = new \DateTimeImmutable();
  8213.         $row 2;
  8214.         foreach ($rdvs as $rdv) {
  8215.             $dateRdv $rdv->getDate();
  8216.             $joursEcoules $dateRdv->diff($today)->days;
  8217.             $client $rdv->getIdClient();
  8218.             $centre $rdv->getIdCentre();
  8219.             $etat $rdv->getIdEtat();
  8220.             $sheet->fromArray([
  8221.                 $rdv->getId(),
  8222.                 $dateRdv->format('d/m/Y H:i'),
  8223.                 $joursEcoules ' jours',
  8224.                 $etat $etat->getLibelle() : 'Non défini',
  8225.                 $client $client->getName() . ' ' $client->getLastname() : '',
  8226.                 $client $client->getPhone() : '',
  8227.                 $client && $client->getClientStatus() ? $client->getClientStatus()->getLibelle() : 'Non défini',
  8228.                 $centre $centre->getName() : '',
  8229.                 $centre $centre->getPhone() : '',
  8230.                 $centre $centre->getAddress() . ', ' $centre->getPostale() . ' ' $centre->getCity() : '',
  8231.                 $rdv->getIdAudio() ? $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastname() : '',
  8232.             ], null'A' $row);
  8233.             $row++;
  8234.         }
  8235.         $writer = new Xlsx($spreadsheet);
  8236.         $filename "rdvs-$startDate-to-$endDate.xlsx";
  8237.         // Stream the file to browser
  8238.         $response = new \Symfony\Component\HttpFoundation\StreamedResponse(function () use ($writer) {
  8239.             $writer->save('php://output');
  8240.         });
  8241.         $dispositionHeader $response->headers->makeDisposition(
  8242.             \Symfony\Component\HttpFoundation\ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  8243.             $filename
  8244.         );
  8245.         $response->headers->set('Content-Type''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  8246.         $response->headers->set('Content-Disposition'$dispositionHeader);
  8247.         return $response;
  8248.     }
  8249.     /**
  8250.      * 
  8251.      * @Route("/optical/rdv/export/excel/{startDate}/{endDate}", name="optical_rdv_export_excel", methods={"GET"})
  8252.      */
  8253.     public function exportOpticalExcelFromDate(string $startDatestring $endDate): Response
  8254.     {
  8255.         $start = new \DateTimeImmutable($startDate);
  8256.         $end = new \DateTimeImmutable($endDate);
  8257.         $rdvs $this->rdvRepository->findOpticalBySinceDateAndMyAudio($start$end);
  8258.         $spreadsheet = new Spreadsheet();
  8259.         $sheet $spreadsheet->getActiveSheet();
  8260.         // Headers
  8261.         $sheet->fromArray([
  8262.             'ID du RDV',
  8263.             'Date du RDV',
  8264.             'Jours écoulés',
  8265.             'Statut RDV',
  8266.             'Nom patient',
  8267.             'Téléphone patient',
  8268.             'Statut patient',
  8269.             'Centre',
  8270.             'Téléphone Centre',
  8271.             'Adresse',
  8272.             'Nom Audio'
  8273.         ], null'A1');
  8274.         $today = new \DateTimeImmutable();
  8275.         $row 2;
  8276.         foreach ($rdvs as $rdv) {
  8277.             $dateRdv $rdv->getDate();
  8278.             $joursEcoules $dateRdv->diff($today)->days;
  8279.             $client $rdv->getIdClient();
  8280.             $centre $rdv->getIdCentre();
  8281.             $etat $rdv->getIdEtat();
  8282.             $sheet->fromArray([
  8283.                 $rdv->getId(),
  8284.                 $dateRdv->format('d/m/Y H:i'),
  8285.                 $joursEcoules ' jours',
  8286.                 $etat $etat->getLibelle() : 'Non défini',
  8287.                 $client $client->getName() . ' ' $client->getLastname() : '',
  8288.                 $client $client->getPhone() : '',
  8289.                 $client && $client->getClientStatus() ? $client->getClientStatus()->getLibelle() : 'Non défini',
  8290.                 $centre $centre->getName() : '',
  8291.                 $centre $centre->getPhone() : '',
  8292.                 $centre $centre->getAddress() . ', ' $centre->getPostale() . ' ' $centre->getCity() : '',
  8293.                 $rdv->getIdAudio() ? $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastname() : '',
  8294.             ], null'A' $row);
  8295.             $row++;
  8296.         }
  8297.         $writer = new Xlsx($spreadsheet);
  8298.         $filename "rdvs-$startDate-to-$endDate.xlsx";
  8299.         // Stream the file to browser
  8300.         $response = new \Symfony\Component\HttpFoundation\StreamedResponse(function () use ($writer) {
  8301.             $writer->save('php://output');
  8302.         });
  8303.         $dispositionHeader $response->headers->makeDisposition(
  8304.             \Symfony\Component\HttpFoundation\ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  8305.             $filename
  8306.         );
  8307.         $response->headers->set('Content-Type''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  8308.         $response->headers->set('Content-Disposition'$dispositionHeader);
  8309.         return $response;
  8310.     }
  8311.     /**
  8312.      * 
  8313.      * @Route("/admin/update-note", name="update_note", methods={"POST"})
  8314.      */
  8315.     public function updateNote(Request $requestEntityManagerInterface $em): JsonResponse
  8316.     {
  8317.         $data json_decode($request->getContent(), true);
  8318.         $id $data['id'] ?? null;
  8319.         $note $data['note'] ?? null;
  8320.         if (!$id || $note === null) {
  8321.             return new JsonResponse(['status' => 'error''message' => 'Invalid data'], 400);
  8322.         }
  8323.         $entity $em->getRepository(Rdv::class)->find($id);
  8324.         if (!$entity) {
  8325.             return new JsonResponse(['status' => 'error''message' => 'Entity not found'], 404);
  8326.         }
  8327.         $entity->setNote($note);
  8328.         $em->flush();
  8329.         return new JsonResponse(['status' => 'success']);
  8330.     }
  8331.     /**
  8332.      * 
  8333.      * @Route("/giuili-admin/edit-rdv/{rdvId}/centre/{centreId}", name="update_admin_rdv", methods={"GET"})
  8334.      */
  8335.     public function showRdvCentre(int $rdvIdCentre $centreId): Response
  8336.     {
  8337.         // dd("tets");
  8338.         $center $centres $this->getDoctrine()
  8339.             ->getRepository(AudioCentre::class)
  8340.             ->findOneBy(['id_centre' => $centreId->getId()]);
  8341.         $audio $center->getIdAudio();
  8342.         $motifs $this->getDoctrine()->getRepository(AudioMotif::class)
  8343.             ->findBy(['id_audio' => $audio'isDeleted' => 0]);
  8344.         return $this->render('easyadmin/rdv/centre_show.html.twig', [
  8345.             'audio' => $audio,
  8346.             'rdvId' => $rdvId,
  8347.             'centreId' => $centreId,
  8348.             'motifs' => $motifs,
  8349.         ]);
  8350.     }
  8351.     
  8352.     /**
  8353.      * 
  8354.      * @Route("/optical-center/edit-rdv/{rdvId}/centre/{centreId}", name="update_optical_rdv", methods={"GET"})
  8355.      */
  8356.     public function showRdvCentreOptical(int $rdvIdCentre $centreId): Response
  8357.     {
  8358.         // dd("tets");
  8359.         $center $centres $this->getDoctrine()
  8360.             ->getRepository(AudioCentre::class)
  8361.             ->findOneBy(['id_centre' => $centreId->getId()]);
  8362.         $audio $center->getIdAudio();
  8363.         $motifs $this->getDoctrine()->getRepository(AudioMotif::class)
  8364.             ->findBy(['id_audio' => $audio'isDeleted' => 0]);
  8365.         return $this->render('easyadmin/rdv/centre_show.html.twig', [
  8366.             'audio' => $audio,
  8367.             'rdvId' => $rdvId,
  8368.             'centreId' => $centreId,
  8369.             'motifs' => $motifs,
  8370.         ]);
  8371.     }
  8372.     /**
  8373.      * @Route("/update-rdv-easyadmin", name="update_rdv_easyadmin", methods={"POST"})
  8374.      */
  8375.     public function updateRdvEasyadmin(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendarRdvSmsService $rdvSms): Response
  8376.     {
  8377.         $data json_decode($request->getContent(), true);
  8378.         $rdv $this->getDoctrine()
  8379.             ->getRepository(Rdv::class)
  8380.             ->find($data["rdv_id"]);
  8381.         $pastDate $rdv->getDate();
  8382.         $entityManager $this->getDoctrine()->getManager();
  8383.         if (isset($data["etat_id"])) {
  8384.             $etat $this->getDoctrine()
  8385.                 ->getRepository(EtatRdv::class)
  8386.                 ->findOneBy(['id' => $data["etat_id"]]);
  8387.             if ($etat == null) {
  8388.                 return new Response(json_encode(([
  8389.                     'message' => 'Error, no etat found at this id',
  8390.                     'path' => 'src/Controller/TrustedUserController.php',
  8391.                     "status" => 400,
  8392.                 ])), 400);
  8393.             }
  8394.             $rdv->setIdEtat($etat);
  8395.         }
  8396.         if (isset($data["audio_id"])) {
  8397.             $audio $this->getDoctrine()
  8398.                 ->getRepository(Audio::class)
  8399.                 ->findOneBy(['id' => $data["audio_id"]]);
  8400.             if ($audio == null) {
  8401.                 return new Response(json_encode(([
  8402.                     'message' => 'Error, no audio found at this id',
  8403.                     'path' => 'src/Controller/TrustedUserController.php',
  8404.                     "status" => 400,
  8405.                 ])), 400);
  8406.             }
  8407.             $rdv->setIdAudio($audio);
  8408.         }
  8409.         if (isset($data["motif_id"])) {
  8410.             $motif $this->getDoctrine()
  8411.                 ->getRepository(Motif::class)
  8412.                 ->find($data["motif_id"]);
  8413.             if ($motif == null) {
  8414.                 return new Response(json_encode(([
  8415.                     'message' => 'Error, no motif found at this id',
  8416.                     'path' => 'src/Controller/TrustedUserController.php',
  8417.                     "status" => 400,
  8418.                 ])), 400);
  8419.             }
  8420.             $rdv->setIdMotif($motif);
  8421.         }
  8422.         if (isset($data["client_id"])) {
  8423.             $client $this->getDoctrine()
  8424.                 ->getRepository(Client::class)
  8425.                 ->findOneBy(['id' => $data["client_id"]]);
  8426.             if ($client == null) {
  8427.                 return new Response(json_encode(([
  8428.                     'message' => 'Error, no client found at this id',
  8429.                     'path' => 'src/Controller/TrustedUserController.php',
  8430.                     "status" => 400,
  8431.                 ])), 400);
  8432.             }
  8433.             $rdv->setIdClient($client);
  8434.         }
  8435.         if (isset($data["date"])) {
  8436.             $data["date"] = str_replace("h"":"$data["date"]);
  8437.             $date \DateTime::createFromFormat("Y-m-d\TH:i"$data["date"]);
  8438.             $audioMotif $this->getDoctrine()
  8439.                 ->getRepository(AudioMotif::class)
  8440.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  8441.             if ($audioMotif == null) {
  8442.                 return new Response(json_encode(([
  8443.                     'message' => 'Error, no motif of this id found at this audio',
  8444.                     'path' => 'src/Controller/RdvController.php',
  8445.                     "status" => 400,
  8446.                 ])), 400);
  8447.             }
  8448.             if ($rdv->getIdAudio()->getIsIndie()) {
  8449.                 if ($rdv->getIdCentre()) {
  8450.                     // regular centre audio indie
  8451.                     /** @var AudioCentre */
  8452.                     $liaison $this->getDoctrine()
  8453.                         ->getRepository(AudioCentre::class)
  8454.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  8455.                     if ($liaison == null) {
  8456.                         return new Response(json_encode(([
  8457.                             'message' => 'Error, audio isnt part of the centre',
  8458.                             'path' => 'src/Controller/RdvController.php',
  8459.                             "status" => 400,
  8460.                         ])), 400);
  8461.                     }
  8462.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  8463.                         return new Response(json_encode(([
  8464.                             'message' => 'Error, no horaire found for this audio',
  8465.                             'path' => 'src/Controller/RdvController.php',
  8466.                             "status" => 400,
  8467.                         ])), 400);
  8468.                     }
  8469.                 } else {
  8470.                     // lieu audio indie
  8471.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  8472.                         return new Response(json_encode(([
  8473.                             'message' => 'Error, no horaire found for this audio',
  8474.                             'path' => 'src/Controller/RdvController.php',
  8475.                             "status" => 400,
  8476.                         ])), 400);
  8477.                     }
  8478.                 }
  8479.             } else {
  8480.                 // regular centre
  8481.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  8482.                     return new Response(json_encode(([
  8483.                         'message' => 'Error, no horaire found for this audio',
  8484.                         'path' => 'src/Controller/RdvController.php',
  8485.                         "status" => 400,
  8486.                     ])), 400);
  8487.                 }
  8488.             }
  8489.             $rdv->setDate($date);
  8490.         }
  8491.         if (isset($data["comment"]) && $token->getIdClient()) {
  8492.             $rdv->setComment($data["comment"]);
  8493.         }
  8494.         if (isset($data["review"]) && $token->getIdClient()) {
  8495.             $rdv->setReview($data["review"]);
  8496.         }
  8497.         if (isset($data["note"])) {
  8498.             $rdv->setNote($data["note"]);
  8499.         }
  8500.         $entityManager->flush();
  8501.         $date $rdv->getDate();
  8502.         $smsDate $date->format('d-m-Y H:i');
  8503.         $oldDate $pastDate->format('d-m-Y H:i');
  8504.         $locale 'fr_FR';
  8505.         $formatter = new IntlDateFormatter(
  8506.             $locale,
  8507.             IntlDateFormatter::FULL,
  8508.             IntlDateFormatter::SHORT,
  8509.             null,
  8510.             IntlDateFormatter::GREGORIAN,
  8511.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  8512.         );
  8513.         $smsDateLongFormat $formatter->format($date);
  8514.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  8515.         $frenchDate ucfirst($frenchDate);
  8516.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  8517.         // notif client
  8518.         if ($rdv->getIdEtat()->getId() != 2) {
  8519.             $params = array(
  8520.                 "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  8521.                 "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  8522.                 "date" => $smsDateLongFormat,
  8523.                 "heure" => substr($smsDate1115),
  8524.                 "motif" => $rdv->getIdMotif()->getTitre(),
  8525.                 "centerName" => $rdv->getIdCentre()->getName(),
  8526.                 "centerAddress" => $rdv->getIdCentre()->getAddress(),
  8527.                 "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  8528.                 "audioMail" => $rdv->getIdAudio()->getMail(),
  8529.                 "centerPhone" => $rdv->getIdCentre()->getPhone(),
  8530.                 "centerCity" => $rdv->getIdCentre()->getCity(),
  8531.                 "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  8532.                 'titre' => 'Votre rendez-vous est modifié pour le',
  8533.                 'frenchDate' => $frenchDate,
  8534.             );
  8535.             $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  8536.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject184);
  8537.             $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.";
  8538.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  8539.         }
  8540.         //     //// == suppression
  8541.         else if ($rdv->getIdEtat()->getId() == 2) {
  8542.             $params = array(
  8543.                 "date" => substr($smsDate010),
  8544.                 "lien" => "{$_ENV['BASE_client']}search",
  8545.                 "heure" => substr($smsDate1115),
  8546.                 "patientName" => $client->getLastName(),
  8547.                 'titre' => 'Votre rendez-vous est annulé :',
  8548.                 'centerName' => $rdv->getIdCentre()->getName(),
  8549.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  8550.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  8551.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  8552.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  8553.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  8554.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  8555.                 'motif' => $rdv->getIdMotif()->getTitre(),
  8556.             );
  8557.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  8558.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject188);
  8559.             if ($data["sms"]) {
  8560.                 $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  8561.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  8562.             }
  8563.         }
  8564.         //notif Audio
  8565.         if ($rdv->getIdEtat()->getId() != 2) {
  8566.             $params = array(
  8567.                 "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  8568.                 "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  8569.                 "date" => substr($smsDate010),
  8570.                 "frenchDate" => $frenchDate,
  8571.                 "heure" => substr($smsDate1115),
  8572.                 'motif' => $rdv->getIdMotif()->getTitre(),
  8573.                 'clientPhone' => $client->getPhone(),
  8574.                 'clientNom' => $client->getLastname(),
  8575.                 'clientPrenom' => $client->getName(),
  8576.                 'clientCivilite' => $client->getCivilite(),
  8577.                 'clientPostal' => $client->getPostal(),
  8578.                 'clientMail' => $client->getMail(),
  8579.                 'centerName' => $rdv->getIdCentre()->getName(),
  8580.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  8581.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  8582.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  8583.                 'idPatient' => $client->getId(),
  8584.                 'proUrl' => "{$_ENV['BASE_logiciel']}",
  8585.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  8586.                 'titre' => 'Votre rendez-vous est modifié pour le :'
  8587.             );
  8588.             $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  8589.             $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  8590.             if ($rdv->getIdAudio()->getModifRdvMail()) {
  8591.                 $subject "🔀 Rendez-vous My Audio modifié du " $frenchDate " à " substr($smsDate1115);
  8592.                 $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject186);
  8593.             }
  8594.             if ($rdv->getIdAudio()->getModifRdvSms()) {
  8595.                 $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.";
  8596.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  8597.             }
  8598.         } else if ($rdv->getIdEtat()->getId() == 2) {
  8599.             $params = array(
  8600.                 "date" => substr($smsDate010),
  8601.                 "lien" => "{$_ENV['BASE_client']}search",
  8602.                 "heure" => substr($smsDate1115),
  8603.                 "patientName" => $client->getLastName(),
  8604.                 'titre' => 'Votre rendez-vous est annulé :',
  8605.                 'centerName' => $rdv->getIdCentre()->getName(),
  8606.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  8607.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  8608.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  8609.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  8610.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  8611.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  8612.                 'motif' => $rdv->getIdMotif()->getTitre(),
  8613.             );
  8614.             $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  8615.             $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  8616.             if ($rdv->getIdAudio()->getModifRdvMail()) {
  8617.                 $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  8618.                 $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject188);
  8619.             }
  8620.             if ($rdv->getIdAudio()->getModifRdvSms()) {
  8621.                 $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.";
  8622.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  8623.             }
  8624.         }
  8625.         /* generate sms notif on update */
  8626.         // update sms notification     
  8627.         $rdvSms->updateRdvSms($rdv);
  8628.         // google calendar update
  8629.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  8630.             ->findBy(array('audio' => $rdv->getIdAudio()));
  8631.         $data['rdv'] = $rdv->getId();
  8632.         $data['motif_id'] = $rdv->getIdMotif();
  8633.         $data['note'] = $rdv->getNote();
  8634.         if ($rdv->getIdClient() !== null) {
  8635.             $data["client_id"] = $rdv->getIdClient()->getId();
  8636.         }
  8637.         if ($rdv->getIdClientTemp() !== null) {
  8638.             $data["client_id_temp"] = $rdv->getIdClientTemp()->getId();
  8639.         }
  8640.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  8641.             ->findBy(array('rdv' => $rdv));
  8642.         foreach ($rdvEvents as $rdvEvent) {
  8643.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  8644.             $googleCalendar->updateEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
  8645.         }
  8646.         return new Response(json_encode(([
  8647.             "id" => $rdv->getId(),
  8648.             "motif_id" => $rdv->getIdMotif()->getId(),
  8649.             "audio_id" => $rdv->getIdAudio()->getId(),
  8650.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  8651.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  8652.             "fullName" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  8653.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  8654.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  8655.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  8656.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  8657.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  8658.             "centre_id" => $rdv->getIdCentre()->getId(),
  8659.             "centerName" => $rdv->getIdCentre()->getName(),
  8660.             "etat_id" => $rdv->getIdEtat()->getId(),
  8661.             "date" => $rdv->getDate(),
  8662.             "comment" => $rdv->getComment(),
  8663.             "note" => $rdv->getNote(),
  8664.             "review" => $rdv->getReview(),
  8665.             "status" => 200,
  8666.         ])));
  8667.     }
  8668.     private function checkRdvReminder($rdv): ?array
  8669.     {
  8670.         $dateRdv $rdv->getDate();
  8671.         $today = new \DateTime();
  8672.         $today->setTime(000);
  8673.         $dateRdv->setTime(000);
  8674.         $intervalDays $today->diff($dateRdv)->days;
  8675.         if ($intervalDays === 1) {
  8676.             $interval "24";
  8677.         } elseif ($intervalDays === 2) {
  8678.             $interval "48";
  8679.         } elseif ($intervalDays === 3) {
  8680.             $interval "72";
  8681.         } elseif ($intervalDays === 4) {
  8682.             $interval "96";
  8683.         } else { // >= 4 jours
  8684.             $interval "92";
  8685.         }
  8686.         $client $rdv->getIdClientTemp() ?: $rdv->getIdClient();
  8687.         $clientId $client $client->getId() : null;
  8688.         $clientName null;
  8689.         if ($client) {
  8690.             $clientName $client->getName() . ' ' $client->getLastName();
  8691.         }
  8692.         $motif $rdv->getIdMotif();
  8693.         $motifTitle $motif $motif->getTitre() : null;
  8694.         $centre $rdv->getIdCentre();
  8695.         $centreName null;
  8696.         if ($centre) {
  8697.             $centreName $centre->getName();
  8698.         }
  8699.         return [
  8700.             'rdvId' => $rdv->getId(),
  8701.             'clientId' => $clientId,
  8702.             'clientName' => $clientName ?? 'N/A',
  8703.             'interval' => $interval,
  8704.             'date' => $rdv->getDate() ? $rdv->getDate()->format('d-m-Y H:i') : null,
  8705.             'motif' => $motifTitle ?? 'N/A',
  8706.             'centreName' => $centreName ?? 'N/A',
  8707.         ];
  8708.     }
  8709. }