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\Token;
  13. use Twig\Environment;
  14. use App\Entity\Centre;
  15. use App\Entity\Client;
  16. use \IntlDateFormatter;
  17. use App\Entity\CallLog;
  18. use App\Entity\EtatRdv;
  19. use App\Entity\LeadRdv;
  20. use App\Entity\Proches;
  21. use App\Entity\LieuTier;
  22. use App\Entity\RdvEvent;
  23. use App\Entity\AudioMotif;
  24. use App\Entity\CentreTier;
  25. use App\Entity\ClientTemp;
  26. use App\Entity\LeadStatus;
  27. use App\Entity\Remplacant;
  28. use App\Entity\TestClient;
  29. use App\Entity\AudioCentre;
  30. use App\Service\SmsHandler;
  31. use App\Entity\AccessCentre;
  32. use App\Entity\ClientStatus;
  33. use Psr\Log\LoggerInterface;
  34. use App\Entity\ClientBlocked;
  35. use App\Entity\CentreMutuelle;
  36. use App\Entity\LieuPrestation;
  37. use App\Entity\AudioSpecialite;
  38. use App\Entity\CallInteraction;
  39. use App\Service\PublicFunction;
  40. use App\Entity\CentrePrestation;
  41. use App\Entity\RegionDepartment;
  42. use App\Repository\RdvRepository;
  43. use Symfony\Component\Mime\Email;
  44. use App\Entity\Device\ClientDevice;
  45. use App\Entity\Notification\RdvSms;
  46. use App\Service\Lead\TwilioService;
  47. use App\Service\Lead\WhatsappService;
  48. use App\Entity\SynchronisationSetting;
  49. use App\Service\Lead\SynthflowService;
  50. use App\Service\Lead\ElevenLabsService;
  51. use Doctrine\ORM\EntityManagerInterface;
  52. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  53. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  54. use Symfony\Contracts\Cache\ItemInterface;
  55. use App\Service\Cosium\ClientCosiumService;
  56. use App\Service\Notification\RdvSmsService;
  57. use App\Entity\SpecificSubscription;
  58. use Symfony\Contracts\Cache\CacheInterface;
  59. use App\Entity\Synchronisation\CosiumCenter;
  60. use App\Service\Lead\AppointmentCallService;
  61. use Symfony\Component\Filesystem\Filesystem;
  62. use Symfony\Component\HttpFoundation\Request;
  63. use Symfony\Component\Mailer\MailerInterface;
  64. use Symfony\Component\HttpFoundation\Response;
  65. use Symfony\Component\Routing\Annotation\Route;
  66. use Doctrine\Common\Collections\ArrayCollection;
  67. use App\EasyAdmin\Controller\DashboardController;
  68. use Symfony\Component\HttpKernel\KernelInterface;
  69. use Symfony\Component\HttpFoundation\JsonResponse;
  70. use App\EasyAdmin\Controller\LeadRdvCrudController;
  71. use App\Service\AdsCompany\RepresentativeCdaService;
  72. use App\Entity\Synchronisation\SynchronisationCosium;
  73. use App\Service\GoogleCalendar\GoogleCalendarService;
  74. use App\EasyAdmin\Controller\RdvMyAudioCrudController;
  75. use App\Service\Notification\EmailNotificationService;
  76. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  77. use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGenerator;
  78. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  79. class RdvController extends AbstractController
  80. {
  81.     private $emailNotificationService;
  82.     private $clientCosiumService;
  83.     private $rdvRepository;
  84.     private $entityManager;
  85.     private $cache;
  86.     private $twig;
  87.     private AdminUrlGenerator $adminUrlGenerator;
  88.     private WhatsappService $whatsapp;
  89.     private LoggerInterface $logger;  // Service de journalisation
  90.     private RdvRepository $rdvRepo;
  91.     public function __construct(CacheInterface $cacheEntityManagerInterface $entityManagerRdvRepository $rdvRepoEmailNotificationService $emailNotificationServiceClientCosiumService $clientCosiumServiceRdvRepository $rdvRepositoryEnvironment $twigAdminUrlGenerator $adminUrlGeneratorWhatsappService $whatsappLoggerInterface $logger)
  92.     {
  93.         $this->entityManager $entityManager;
  94.         $this->emailNotificationService $emailNotificationService;
  95.         $this->clientCosiumService $clientCosiumService;
  96.         $this->rdvRepository $rdvRepository;
  97.         $this->cache $cache;
  98.         $this->twig $twig;
  99.         $this->adminUrlGenerator $adminUrlGenerator;
  100.         $this->whatsapp $whatsapp;
  101.         $this->logger $logger;
  102.         $this->rdvRepo $rdvRepo;
  103.     }
  104.     /**
  105.      * @Route("/rdv/{id}", name="deleteRdvByID", methods={"DELETE"})
  106.      */
  107.     public function deleteRdvByID(Request $requestRdv $rdvGoogleCalendarService $googleCalendar)
  108.     {
  109.         if (!$request->query->get('token')) {
  110.             return new Response(json_encode([
  111.                 "message" => "Pas de token n'a été spécifié",
  112.                 "status" => 401,
  113.             ]), 401);
  114.         }
  115.         $entityManager $this->getDoctrine()->getManager();
  116.         /** @var Token */
  117.         $token $this->getDoctrine()
  118.             ->getRepository(Token::class)
  119.             ->findOneBy(['token' => $request->query->get('token')]);
  120.         if (!$token) {
  121.             return new Response(json_encode([
  122.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  123.                 "status" => 404,
  124.             ]), 404);
  125.         }
  126.         // get token age
  127.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  128.         // if the token if older than 7 days
  129.         if ($dateDiff->7) {
  130.             $entityManager->remove($token);
  131.             $entityManager->flush();
  132.             return $this->json([
  133.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  134.                 'path' => 'src/Controller/ClientController.php',
  135.                 "status" => 401,
  136.             ], 401);
  137.         }
  138.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  139.             return new Response(json_encode([
  140.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  141.                 "status" => 404,
  142.             ]), 404);
  143.         }
  144.         $entityManager->remove($rdv);
  145.         $entityManager->flush();
  146.         return new Response(json_encode(([
  147.             'message' => "Rdv has been successfully deleted",
  148.             "status" => 200,
  149.         ])));
  150.     }
  151.     /**
  152.      * @Route("/rdv/{id}", name="getRdvByID", methods={"GET","HEAD"})
  153.      */
  154.     public function getRdvByID(Request $requestRdv $rdvPublicFunction $publicFunction)
  155.     {
  156.         if (!$request->query->get('token')) {
  157.             return new Response(json_encode([
  158.                 "message" => "Pas de token n'a été spécifié",
  159.                 "status" => 401,
  160.             ]), 401);
  161.         }
  162.         $entityManager $this->getDoctrine()->getManager();
  163.         /** @var Token */
  164.         $token $this->getDoctrine()
  165.             ->getRepository(Token::class)
  166.             ->findOneBy(['token' => $request->query->get('token')]);
  167.         if (!$token) {
  168.             return new Response(json_encode([
  169.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  170.                 "status" => 404,
  171.             ]), 404);
  172.         }
  173.         // get token age
  174.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  175.         // if the token if older than 7 days
  176.         if ($dateDiff->7) {
  177.             $entityManager->remove($token);
  178.             $entityManager->flush();
  179.             return $this->json([
  180.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  181.                 'path' => 'src/Controller/ClientController.php',
  182.                 "status" => 401,
  183.             ], 401);
  184.         }
  185.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  186.             return new Response(json_encode([
  187.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  188.                 "status" => 404,
  189.             ]), 404);
  190.         }
  191.         /** @var AudioCentre */
  192.         $liaison $this->getDoctrine()->getRepository(AudioCentre::class)
  193.             ->findOneBy(array('id_audio' => $rdv->getIdAudio(), 'id_centre' => $rdv->getIdCentre(), 'isConfirmed' => true));
  194.         // Motif filter
  195.         /** @var AudioMotif[] */
  196.         $motifs $this->getDoctrine()->getRepository(AudioMotif::class)
  197.             ->findBy(array('id_audio' => $rdv->getIdAudio(), 'id_motif' => $rdv->getIdMotif()));
  198.         $resultMotif = new ArrayCollection();
  199.         foreach ($motifs as $motif) {
  200.             $resultMotif->add([
  201.                 "id" => $motif->getIdMotif()->getId(),
  202.                 "titre" => $motif->getIdMotif()->getTitre(),
  203.                 "consigne" => $motif->getConsigne(),
  204.                 "duration" => $motif->getDuration(),
  205.             ]);
  206.         }
  207.         // Specialities
  208.         /** @var AudioSpecialite[] */
  209.         $specialities $this->getDoctrine()->getRepository(AudioSpecialite::class)
  210.             ->findBy(array('id_audio' => $rdv->getIdAudio()));
  211.         $resultSpeciality = new ArrayCollection();
  212.         foreach ($specialities as $speciality) {
  213.             $resultSpeciality->add([
  214.                 "id" => $speciality->getIdSpecialite()->getId(),
  215.                 "titre" => $speciality->getIdSpecialite()->getLibelle(),
  216.             ]);
  217.         }
  218.         if ($rdv->getIdCentre())
  219.         /** @var AccessCentre*/
  220.         {
  221.             $accessCentre $this->getDoctrine()->getRepository(AccessCentre::class)
  222.                 ->findOneBy(array('id_centre' => $rdv->getIdCentre()));
  223.         } else
  224.         /** @var AccessCentre*/
  225.         {
  226.             $accessCentre $this->getDoctrine()->getRepository(AccessCentre::class)
  227.                 ->findOneBy(array('id_lieu' => $rdv->getIdLieu()));
  228.         }
  229.         if ($rdv->getIdCentre())
  230.         /** @var CentrePrestation[]*/
  231.         {
  232.             $prestations $this->getDoctrine()->getRepository(CentrePrestation::class)
  233.                 ->findBy(array('id_centre' => $liaison->getIdCentre()->getId()));
  234.         } else
  235.         /** @var LieuPrestation[]*/
  236.         {
  237.             $prestations $this->getDoctrine()->getRepository(LieuPrestation::class)
  238.                 ->findBy(array('id_lieu' => $rdv->getIdLieu()));
  239.         }
  240.         $resultPrestation = new ArrayCollection();
  241.         foreach ($prestations as $prestation) {
  242.             $resultPrestation->add([
  243.                 "id" => $prestation->getIdPrestation()->getId(),
  244.                 "titre" => $prestation->getIdPrestation()->getLibelle(),
  245.             ]);
  246.         }
  247.         $mutuelles $this->getDoctrine()->getRepository(CentreMutuelle::class)
  248.             ->findBy(array('id_centre' => $rdv->getIdCentre()));
  249.         $resultMutuelle = new ArrayCollection();
  250.         foreach ($mutuelles as $mutuelle) {
  251.             $resultMutuelle->add([
  252.                 "id" => $mutuelle->getIdMutuelle()->getId(),
  253.                 "titre" => $mutuelle->getIdMutuelle()->getLibelle(),
  254.             ]);
  255.         }
  256.         if ($rdv->getIdCentre())
  257.         /** @var CentreTier[]*/
  258.         {
  259.             $tiers $this->getDoctrine()->getRepository(CentreTier::class)
  260.                 ->findBy(array('id_centre' => $liaison->getIdCentre()->getId()));
  261.         } else
  262.         /** @var LieuTier[]*/
  263.         {
  264.             $tiers $this->getDoctrine()->getRepository(LieuTier::class)
  265.                 ->findBy(array('id_lieu' => $rdv->getIdLieu()));
  266.         }
  267.         $resultTier = new ArrayCollection();
  268.         foreach ($tiers as $tier) {
  269.             $resultTier->add([
  270.                 "id" => $tier->getIdTier()->getId(),
  271.                 "titre" => $tier->getIdTier()->getLibelle(),
  272.             ]);
  273.         }
  274.         $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  275.         /** @var Rdv[] */
  276.         $audioRdvs $this->getDoctrine()->getRepository(Rdv::class)
  277.             ->findAllReviewsAudio($rdv->getIdAudio()->getId());
  278.         /** @var Rdv[] */
  279.         $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  280.             ->findAllReviewsCentre($rdvCentre->getId());
  281.         // Comment
  282.         /** @var Rdv[] */
  283.         $rdvs $this->getDoctrine()->getRepository(Rdv::class)
  284.             ->findBy(array('id_audio' => $rdv->getIdAudio()));
  285.         $comments = [];
  286.         foreach ($rdvs as $rdv)
  287.             if ($rdv->getComment() && $rdv->getReview() && $rdv->getIdClient())
  288.                 array_push($comments, [
  289.                     "id" => $rdv->getIdClient()->getId(),
  290.                     "name" => $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname()[0] . ".",
  291.                     "comment" => $rdv->getComment(),
  292.                     "isMale" => $rdv->getIdClient()->getCivilite() == "Monsieur",
  293.                     "review" => $rdv->getReview(),
  294.                 ]);
  295.         return new Response(json_encode(([
  296.             "id" => $rdv->getId(),
  297.             "motif_id" => $rdv->getIdMotif()->getId(),
  298.             "motif_titre" => $rdv->getIdMotif()->getTitre(),
  299.             "audio_id" => $rdv->getIdAudio()->getId(),
  300.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  301.             "client_id" => $rdv->getIdClient()->getId(),
  302.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  303.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  304.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  305.             "etat_id" => $rdv->getIdEtat()->getId(),
  306.             "date" => $rdv->getDate(),
  307.             "comment" => $rdv->getComment(),
  308.             "review" => $rdv->getReview(),
  309.             "note" => $rdv->getNote(),
  310.             "testclient" => $rdv->getTestClient() ? [
  311.                 "result" => $rdv->getTestClient()->getResultTonal(),
  312.                 "date" => $rdv->getTestClient()->getDate(),
  313.                 "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  314.             ] : null,
  315.             "comments" => $comments,
  316.             "audio" => [
  317.                 "id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : $rdv->getIdAudio()->getId(),
  318.                 "civilite" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getCivilite() : $rdv->getIdAudio()->getCivilite(),
  319.                 "name" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getName() : $rdv->getIdAudio()->getName(),
  320.                 "lastname" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getLastname() : $rdv->getIdAudio()->getLastname(),
  321.                 "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  322.                 "mail" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getMail() : $rdv->getIdAudio()->getMail(),
  323.                 "phone" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getPhone() : $rdv->getIdAudio()->getPhone(),
  324.                 "adeli" => $rdv->getIdAudio()->getAdeli(),
  325.                 "pin" => $rdv->getIdAudio()->getPin(),
  326.                 "description" => $rdv->getIdAudio()->getDescription(),
  327.                 "averageRating" => $publicFunction->calculateRating($audioRdvs),
  328.                 "nbrReview" => count($audioRdvs),
  329.                 "motifs" => $resultMotif->toArray(),
  330.                 "specialities" => $resultSpeciality->toArray(),
  331.             ],
  332.             "centre" => [
  333.                 "id" => $rdvCentre->getId(),
  334.                 "audio_id" => $rdvCentre->getIdGerant()->getId(),
  335.                 "name" => $rdvCentre->getName(),
  336.                 "imgUrl" => $rdvCentre->getImgUrl(),
  337.                 "isRdvDomicile" => $rdv->getIdCentre() ? $rdvCentre->getIsRdvDomicile() : $rdv->getIdAudio()->getIsRdvDomicileIndie(),
  338.                 "address" => $rdvCentre->getAddress(),
  339.                 "postale" => $rdvCentre->getPostale(),
  340.                 "city" => $rdvCentre->getCity(),
  341.                 "finess" => $rdvCentre->getFiness(),
  342.                 "siret" => $rdvCentre->getSiret(),
  343.                 "website" => $rdvCentre->getWebsite(),
  344.                 "phone" => $rdvCentre->getPhone(),
  345.                 "isHandicap" => $rdvCentre->getIsHandicap(),
  346.                 "longitude" => $rdvCentre->getLongitude(),
  347.                 "latitude" => $rdvCentre->getLatitude(),
  348.                 "averageRating" => $publicFunction->calculateRating($centreRdvs),
  349.                 "nbrReview" => count($centreRdvs),
  350.                 "tram" => $accessCentre->getTram(),
  351.                 "rer" => $accessCentre->getRer(),
  352.                 "metro" => $accessCentre->getMetro(),
  353.                 "bus" => $accessCentre->getBus(),
  354.                 "parking" => $accessCentre->getParkingPublic(),
  355.                 "description" => $rdv->getIdCentre()->getDescription(),
  356.                 "parkingPrivate" => $accessCentre->getParkingPrivate(),
  357.                 "other" => $accessCentre->getOther(),
  358.                 "prestations" => $resultPrestation->toArray(),
  359.                 "mutuelles" => $resultMutuelle->toArray(),
  360.                 "tiers" => $resultTier->toArray(),
  361.                 "isLieu" => false,
  362.                 "schedule" => $rdv->getIdAudio()->getIsIndie() == false $rdv->getIdCentre()->getHoraire() : ($rdv->getIdLieu() ? $rdv->getIdLieu()->getHoraire() : $liaison->getHoraire()),
  363.             ],
  364.             "status" => 200,
  365.         ])));
  366.     }
  367.     /**
  368.      * @Route("/rdvs/client/{id}", name="getRdvsByClientID", methods={"GET","HEAD"})
  369.      */
  370.     public function getRdvsByClientID(Request $requestClient $clientPublicFunction $publicFunction)
  371.     {
  372.         if (!$request->query->get('token')) {
  373.             return new Response(json_encode([
  374.                 "message" => "Pas de token n'a été spécifié",
  375.                 "status" => 401,
  376.             ]), 401);
  377.         }
  378.         $entityManager $this->getDoctrine()->getManager();
  379.         /** @var Token */
  380.         $token $this->getDoctrine()
  381.             ->getRepository(Token::class)
  382.             ->findOneBy(['token' => $request->query->get('token')]);
  383.         if (!$token) {
  384.             return new Response(json_encode([
  385.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  386.                 "status" => 404,
  387.             ]), 404);
  388.         }
  389.         // get token age
  390.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  391.         // if the token if older than 7 days
  392.         if ($dateDiff->7) {
  393.             $entityManager->remove($token);
  394.             $entityManager->flush();
  395.             return $this->json([
  396.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  397.                 'path' => 'src/Controller/ClientController.php',
  398.                 "status" => 401,
  399.             ], 401);
  400.         }
  401.         if ($token->getIdClient()) {
  402.             if ($client != $token->getIdClient()) {
  403.                 return new Response(json_encode([
  404.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  405.                     "status" => 404,
  406.                 ]), 404);
  407.             }
  408.         } else if ($token->getIdAudio()) {
  409.             /** @var Token */
  410.             $token $this->getDoctrine()
  411.                 ->getRepository(Rdv::class)
  412.                 ->findOneBy(['id_client' => $client'id_audio' => $token->getIdAudio()]);
  413.             if ($client != $token->getIdClient()) {
  414.                 return new Response(json_encode([
  415.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  416.                     "status" => 404,
  417.                 ]), 404);
  418.             }
  419.         } else {
  420.             return new Response(json_encode([
  421.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  422.                 "status" => 404,
  423.             ]), 404);
  424.         }
  425.         if ($request->query->get('audio')) {
  426.             /** @var Rdv[] */
  427.             $rdvs $this->getDoctrine()
  428.                 ->getRepository(Rdv::class)
  429.                 ->findBy(['id_client' => $client->getId(), 'id_audio' => $token->getIdAudio()]);
  430.             $rdvResult = new ArrayCollection();
  431.         } else {
  432.             /** @var Rdv[] */
  433.             $rdvs $this->getDoctrine()
  434.                 ->getRepository(Rdv::class)
  435.                 ->findBy(['id_client' => $client->getId()]);
  436.             $rdvResult = new ArrayCollection();
  437.         }
  438.         if ($request->query->get('old')) {
  439.             $oldRdvResult = new ArrayCollection();
  440.         }
  441.         foreach ($rdvs as $rdv) {
  442.             if ($rdv->getIdEtat()->getId() != 1) {
  443.                 continue;
  444.             }
  445.             /** @var AudioMotif */
  446.             $audioMotif $this->getDoctrine()
  447.                 ->getRepository(AudioMotif::class)
  448.                 ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  449.             if (!$audioMotif) {
  450.                 continue;
  451.             }
  452.             $duration '';
  453.             if (is_null($rdv->getDuration())) {
  454.                 $duration $audioMotif->getDuration();
  455.             } else {
  456.                 $duration $rdv->getDuration();
  457.             }
  458.             $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  459.             /** @var Rdv[] */
  460.             $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  461.                 ->findAllReviewsCentre($rdvCentre->getId());
  462.             $rdvItem = [
  463.                 "id" => $rdv->getId(),
  464.                 "motif_id" => $rdv->getIdMotif()->getId(),
  465.                 "duration" => $duration,
  466.                 "color" => $audioMotif->getColor(),
  467.                 "audio_id" => $rdv->getIdAudio()->getId(),
  468.                 "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  469.                 "audio_name" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getName() . " " $rdv->getRemplacant()->getLastname() : $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  470.                 "client_id" => $rdv->getIdClient()->getId(),
  471.                 "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() . " " $rdv->getIdProche()->getLastname() : $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname(),
  472.                 "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  473.                 "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  474.                 "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  475.                 "testclient" => $rdv->getTestClient() ? [
  476.                     "result" => $rdv->getTestClient()->getResultTonal(),
  477.                     "date" => $rdv->getTestClient()->getDate(),
  478.                     "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  479.                 ] : null,
  480.                 "name" => $rdvCentre->getName(),
  481.                 "phone" => $rdvCentre->getPhone(),
  482.                 "imgUrl" => $rdvCentre->getImgUrl(),
  483.                 "address" => $rdvCentre->getAddress(),
  484.                 "postale" => $rdvCentre->getPostale(),
  485.                 "city" => $rdvCentre->getCity(),
  486.                 "etat_id" => $rdvCentre->getId(),
  487.                 "averageRating" => $publicFunction->calculateRating($centreRdvs),
  488.                 "nbrReview" => count($centreRdvs),
  489.                 "acceptedCurrency" => "CB Chèque",
  490.                 "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  491.                 "note" => $rdv->getNote(),
  492.                 "comment" => $rdv->getComment(),
  493.                 "review" => $rdv->getReview(),
  494.             ];
  495.             if ($rdv->getDate() >= new DateTime()) {
  496.                 $rdvResult->add($rdvItem);
  497.             } else if ($request->query->get('old')) {
  498.                 $oldRdvResult->add($rdvItem);
  499.             }
  500.         }
  501.         if ($request->query->get('old')) {
  502.             if ($request->query->get('onlyOld')) {
  503.                 if (count($rdvResult) > || count($oldRdvResult) > 0) {
  504.                     return new Response(json_encode(([
  505.                         "oldRdv" => $oldRdvResult->toArray(),
  506.                         "status" => 200,
  507.                     ])));
  508.                 } else {
  509.                     return new Response(json_encode(([
  510.                         "message" => "Aucun rendez-vous n'a été trouvé!",
  511.                         "test" => "count:" count($rdvs),
  512.                         'path' => 'src/Controller/RdvController.php',
  513.                         "rdv" => array(),
  514.                         "oldRdv" => array(),
  515.                         "status" => 404,
  516.                     ])));
  517.                 }
  518.             } else {
  519.                 if (count($rdvResult) > || count($oldRdvResult) > 0) {
  520.                     return new Response(json_encode(([
  521.                         "rdv" => $rdvResult->toArray(),
  522.                         "oldRdv" => $oldRdvResult->toArray(),
  523.                         "status" => 200,
  524.                     ])));
  525.                 } else {
  526.                     return new Response(json_encode(([
  527.                         "message" => "Aucun rendez-vous n'a été trouvé!",
  528.                         "test" => "count:" count($rdvs),
  529.                         'path' => 'src/Controller/RdvController.php',
  530.                         "rdv" => array(),
  531.                         "oldRdv" => array(),
  532.                         "status" => 404,
  533.                     ])));
  534.                 }
  535.             }
  536.         } else {
  537.             if (count($rdvResult) > 0) {
  538.                 return new Response(json_encode(([
  539.                     "content" => $rdvResult->toArray(),
  540.                     "status" => 200,
  541.                 ])));
  542.             } else {
  543.                 return new Response(json_encode(([
  544.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  545.                     "test" => "count2:" count($rdvs),
  546.                     'path' => 'src/Controller/RdvController.php',
  547.                     "status" => 404,
  548.                 ])));
  549.             }
  550.         }
  551.     }
  552.     /**
  553.      * @Route("/rdvs/client/{id}/centre", name="getRdvsByClientIDForCentre", methods={"GET","HEAD"})
  554.      */
  555.     public function getRdvsByClientIDForCentre(Request $requestClient $clientPublicFunction $publicFunction)
  556.     {
  557.         if (!$request->query->get('token')) {
  558.             return new Response(json_encode([
  559.                 "message" => "Pas de token n'a été spécifié",
  560.                 "status" => 401,
  561.             ]), 401);
  562.         }
  563.         $entityManager $this->getDoctrine()->getManager();
  564.         /** @var Token */
  565.         $token $this->getDoctrine()
  566.             ->getRepository(Token::class)
  567.             ->findOneBy(['token' => $request->query->get('token')]);
  568.         if (!$token) {
  569.             return new Response(json_encode([
  570.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  571.                 "status" => 404,
  572.             ]), 404);
  573.         }
  574.         $audio $this->getDoctrine()
  575.             ->getRepository(Audio::class)
  576.             ->findOneBy(['id' => $request->query->get('audio')]);
  577.         $audioCentre $this->getDoctrine()
  578.             ->getRepository(AudioCentre::class)
  579.             ->findOneBy(['id_audio' => $audio]);
  580.         // get token age
  581.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  582.         // if the token if older than 7 days
  583.         if ($dateDiff->7) {
  584.             $entityManager->remove($token);
  585.             $entityManager->flush();
  586.             return $this->json([
  587.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  588.                 'path' => 'src/Controller/ClientController.php',
  589.                 "status" => 401,
  590.             ], 401);
  591.         }
  592.         if ($token->getIdClient()) {
  593.             if ($client != $token->getIdClient()) {
  594.                 return new Response(json_encode([
  595.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  596.                     "status" => 404,
  597.                 ]), 404);
  598.             }
  599.         } else if ($token->getIdAudio()) {
  600.             /** @var Token */
  601.             if ($token->getIdAudio() != $audio) {
  602.                 return new Response(json_encode([
  603.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  604.                     "status" => 404,
  605.                 ]), 404);
  606.             }
  607.         } else {
  608.             return new Response(json_encode([
  609.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  610.                 "status" => 404,
  611.             ]), 404);
  612.         }
  613.         if ($request->query->get('centre')) {
  614.             /** @var Rdv[] */
  615.             $rdvs $this->getDoctrine()
  616.                 ->getRepository(Rdv::class)
  617.                 ->findBy(['id_client' => $client->getId(), 'id_centre' => $audioCentre->getIdCentre()]);
  618.             $rdvResult = new ArrayCollection();
  619.         } else {
  620.             /** @var Rdv[] */
  621.             $rdvs $this->getDoctrine()
  622.                 ->getRepository(Rdv::class)
  623.                 ->findBy(['id_client' => $client->getId()]);
  624.             $rdvResult = new ArrayCollection();
  625.         }
  626.         if ($request->query->get('old')) {
  627.             $oldRdvResult = new ArrayCollection();
  628.         }
  629.         foreach ($rdvs as $rdv) {
  630.             /*if ($rdv->getIdEtat()->getId() != 1) {
  631.                 continue;
  632.             }*/
  633.             /** @var AudioMotif */
  634.             $audioMotif $this->getDoctrine()
  635.                 ->getRepository(AudioMotif::class)
  636.                 ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  637.             if (!$audioMotif) {
  638.                 continue;
  639.             }
  640.             $duration '';
  641.             if (is_null($rdv->getDuration())) {
  642.                 $duration $audioMotif->getDuration();
  643.             } else {
  644.                 $duration $rdv->getDuration();
  645.             }
  646.             $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  647.             /** @var Rdv[] */
  648.             $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  649.                 ->findAllReviewsCentre($rdvCentre->getId());
  650.             $rdvItem = [
  651.                 "id" => $rdv->getId(),
  652.                 "motif_id" => $rdv->getIdMotif()->getId(),
  653.                 "duration" => $duration,
  654.                 "color" => $audioMotif->getColor(),
  655.                 "audio_id" => $rdv->getIdAudio()->getId(),
  656.                 "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  657.                 "audio_name" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getName() . " " $rdv->getRemplacant()->getLastname() : $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  658.                 "client_id" => $rdv->getIdClient()->getId(),
  659.                 "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() . " " $rdv->getIdProche()->getLastname() : $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname(),
  660.                 "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  661.                 "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  662.                 "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  663.                 "testclient" => $rdv->getTestClient() ? [
  664.                     "result" => $rdv->getTestClient()->getResultTonal(),
  665.                     "date" => $rdv->getTestClient()->getDate(),
  666.                     "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  667.                 ] : null,
  668.                 "name" => $rdvCentre->getName(),
  669.                 "phone" => $rdvCentre->getPhone(),
  670.                 "imgUrl" => $rdvCentre->getImgUrl(),
  671.                 "address" => $rdvCentre->getAddress(),
  672.                 "postale" => $rdvCentre->getPostale(),
  673.                 "city" => $rdvCentre->getCity(),
  674.                 "etat_id" => $rdvCentre->getId(),
  675.                 "averageRating" => $publicFunction->calculateRating($centreRdvs),
  676.                 "nbrReview" => count($centreRdvs),
  677.                 "acceptedCurrency" => "CB Chèque",
  678.                 "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  679.                 "note" => $rdv->getNote(),
  680.                 "comment" => $rdv->getComment(),
  681.                 "review" => $rdv->getReview(),
  682.                 "status" => $rdv->getIdEtat()->getLibelle()
  683.             ];
  684.             // dd(new DateTime());
  685.             if ($rdv->getDate() >= new DateTime()) {
  686.                 $rdvResult->add($rdvItem);
  687.             } else if ($request->query->get('old')) {
  688.                 $oldRdvResult->add($rdvItem);
  689.             }
  690.         }
  691.         if ($request->query->get('old')) {
  692.             if (count($rdvResult) > || count($oldRdvResult) > 0) {
  693.                 return new Response(json_encode(([
  694.                     "rdv" => $rdvResult->toArray(),
  695.                     "oldRdv" => $oldRdvResult->toArray(),
  696.                     "status" => 200,
  697.                 ])));
  698.             } else {
  699.                 return new Response(json_encode(([
  700.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  701.                     "test" => "count:" count($rdvs),
  702.                     'path' => 'src/Controller/RdvController.php',
  703.                     "status" => 404,
  704.                 ])), 404);
  705.             }
  706.         } else {
  707.             if (count($rdvResult) > 0) {
  708.                 return new Response(json_encode(([
  709.                     "content" => $rdvResult->toArray(),
  710.                     "status" => 200,
  711.                 ])));
  712.             } else {
  713.                 return new Response(json_encode(([
  714.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  715.                     "test" => "count2:" count($rdvs),
  716.                     'path' => 'src/Controller/RdvController.php',
  717.                     "status" => 404,
  718.                 ])));
  719.             }
  720.         }
  721.     }
  722.     /////// CRON
  723.     /**
  724.      * @Route("/confirmRdvSms", name="confirmRdvSms", methods={"GET","HEAD"})
  725.      */
  726.     public function confirmRdvSms(PublicFunction $publicFunction): Response
  727.     {
  728.         $date = new DateTime();
  729.         $minutes_to_add 30;
  730.         $date->add(new DateInterval('PT' $minutes_to_add 'M'));
  731.         $date->setTimezone(new DateTimeZone('Europe/Paris'));
  732.         $currentDate $date->format('Y-m-d H:i:00');
  733.         $toSend $this->getDoctrine()->getRepository(Rdv::class)
  734.             ->findRdvsIn10Mins($currentDate);
  735.         $entityManager $this->getDoctrine()->getManager();
  736.         $rdvResult = new ArrayCollection();
  737.         foreach ($toSend as $rdv) {
  738.             $date $rdv->getDate();
  739.             // $smsDate = $date->format('d-m-Y H:i');
  740.             //$client = $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  741.             //$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.";
  742.             // // $publicFunction->sendEmail("MyAudio <noreply@myaudio.fr>", $client->getMail(), "My Audio: Testing CRON", "<p>Testing Cron.</p>");
  743.             //$response = $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $client->getPhone(), 4);
  744.             //$another_response = explode(" | ", $response);
  745.             // $idSms = trim($another_response[2]);
  746.             // $rdv->setIdSms($idSms);
  747.             //$entityManager->persist($rdv);
  748.             // $entityManager->flush();
  749.         }
  750.         return new Response(json_encode([
  751.             // "test" => $idSms,
  752.             "currentDate" => $currentDate
  753.         ]));
  754.     }
  755.     /////// CRON 
  756.     /**
  757.      * @Route("/validateRdvSms", name="validateRdvSms", methods={"GET","HEAD"})
  758.      */
  759.     public function validateRdvSms(Request $requestPublicFunction $publicFunction): Response
  760.     {
  761.         $entityManager $this->getDoctrine()->getManager();
  762.         $smsId $_GET['smsID'];
  763.         $message $_GET['message'];
  764.         $callLog $this->getDoctrine()
  765.             ->getRepository(CallLog::class)
  766.             ->findOneBy(['smsId' => $smsId]);
  767.         if ($callLog) {
  768.             $callLog->setAnsweredAt(new \DateTimeImmutable());
  769.             $interaction = new CallInteraction;
  770.             $interaction->setCallLog($callLog);
  771.             try {
  772.                 if ($message == "1") {
  773.                     $interaction->setStep('equipment_status');
  774.                     $interaction->setResponse('réponse_reçue');
  775.                     $interaction->setTimestamp(new \DateTimeImmutable());
  776.                     $interaction->setAdditionalData(['digit' => '1''status' => 'en_essai']);
  777.                     $entityManager->persist($interaction);
  778.                     $sms "Merci pour votre réponse. Nous notons que vous êtes actuellement en période d'essai. Merci et bonne journée avec MyAudio";
  779.                     $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$callLog->getPhoneNumber(), 4);
  780.                 } else if ($message == "2") {
  781.                     $interaction->setStep('equipment_status');
  782.                     $interaction->setResponse('réponse_reçue');
  783.                     $interaction->setTimestamp(new \DateTimeImmutable());
  784.                     $interaction->setAdditionalData(['digit' => '2''status' => 'finalise']);
  785.                     $entityManager->persist($interaction);
  786.                     $sms "Félicitations pour votre appareillage ! Nous sommes ravis que vous ayez finalisé cet achat important. Bonne journée avec My Audio.";
  787.                     $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$callLog->getPhoneNumber(), 4);
  788.                 } else if ($message == "3") {
  789.                     $interaction->setStep('equipment_status');
  790.                     $interaction->setResponse('réponse_reçue');
  791.                     $interaction->setTimestamp(new \DateTimeImmutable());
  792.                     $interaction->setAdditionalData(['digit' => '3''status' => 'abandonne']);
  793.                     $entityManager->persist($interaction);
  794.                     $sms "Nous avons bien noté que vous avez rendu les appareils sans finaliser l'achat. Bonne journée avec My Audio.";
  795.                     $result $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$callLog->getPhoneNumber(), 4);
  796.                     error_log("Résultat envoi SMSSSSSSSSSSSSSSSSSSSSSSSSS: " json_encode($result));
  797.                 } else if ($message == "4") {
  798.                     $interaction->setStep('equipment_status');
  799.                     $interaction->setResponse('réponse_reçue');
  800.                     $interaction->setTimestamp(new \DateTimeImmutable());
  801.                     $interaction->setAdditionalData(['digit' => '4''status' => 'attente_rdv_orl']);
  802.                     $entityManager->persist($interaction);
  803.                     $sms "Nous avons bien noté que vous etes en attente d'un rendez-vous avec un ORL. Bonne journée avec My Audio.";
  804.                     $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$callLog->getPhoneNumber(), 4);
  805.                 } else if ($message == "5") {
  806.                     $interaction->setStep('equipment_status');
  807.                     $interaction->setResponse('réponse_reçue');
  808.                     $interaction->setTimestamp(new \DateTimeImmutable());
  809.                     $interaction->setAdditionalData(['digit' => '5''status' => 'autre']);
  810.                     $entityManager->persist($interaction);
  811.                     $sms "Merci pour votre réponse. Un conseiller My Audio vous contactera dans les prochains jours. Bonne journée.";
  812.                     $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$callLog->getPhoneNumber(), 4);
  813.                 } else {
  814.                     error_log("Message non reconnu: " $message);
  815.                     return new Response(json_encode([
  816.                         "message" => "La réponse spécifiée est incorrecte",
  817.                         "status" => 401,
  818.                         "réponse" => $message,
  819.                     ]), 401);
  820.                 }
  821.                 $entityManager->flush();
  822.                 return new Response(json_encode([
  823.                     "message" => "Réponse traitée avec succès",
  824.                     "status" => 200,
  825.                 ]));
  826.             } catch (\Exception $e) {
  827.                 return new Response(json_encode([
  828.                     "message" => "Erreur lors du traitement de la réponse: " $e->getMessage(),
  829.                     "status" => 500,
  830.                 ]), 500);
  831.             }
  832.         }
  833.         return new Response(json_encode([
  834.             "smsId" => $smsId,
  835.             "message" => $currentDate
  836.         ]));
  837.     }
  838.     /**
  839.      * @Route("/rdvs/old/client/{id}", name="getOldRdvsByClientId", methods={"GET","HEAD"})
  840.      */
  841.     public function getOldRdvsByClientId(Request $requestClient $clientPublicFunction $publicFunction)
  842.     {
  843.         if (!$request->query->get('token')) {
  844.             return new Response(json_encode([
  845.                 "message" => "Pas de token n'a été spécifié",
  846.                 "status" => 401,
  847.             ]), 401);
  848.         }
  849.         $entityManager $this->getDoctrine()->getManager();
  850.         /** @var Token */
  851.         $token $this->getDoctrine()
  852.             ->getRepository(Token::class)
  853.             ->findOneBy(['token' => $request->query->get('token')]);
  854.         if (!$token) {
  855.             return new Response(json_encode([
  856.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  857.                 "status" => 404,
  858.             ]), 404);
  859.         }
  860.         // get token age
  861.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  862.         // if the token if older than 7 days
  863.         if ($dateDiff->7) {
  864.             $entityManager->remove($token);
  865.             $entityManager->flush();
  866.             return $this->json([
  867.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  868.                 'path' => 'src/Controller/ClientController.php',
  869.                 "status" => 401,
  870.             ], 401);
  871.         }
  872.         if ($token->getIdClient()) {
  873.             if ($client != $token->getIdClient()) {
  874.                 return new Response(json_encode([
  875.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  876.                     "status" => 404,
  877.                 ]), 404);
  878.             }
  879.         } else if ($token->getIdAudio()) {
  880.             /** @var Token */
  881.             $token $this->getDoctrine()
  882.                 ->getRepository(Rdv::class)
  883.                 ->findOneBy(['id_client' => $client'id_audio' => $token->getIdAudio()]);
  884.             if ($client != $token->getIdClient()) {
  885.                 return new Response(json_encode([
  886.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  887.                     "status" => 404,
  888.                 ]), 404);
  889.             }
  890.         } else {
  891.             return new Response(json_encode([
  892.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  893.                 "status" => 404,
  894.             ]), 404);
  895.         }
  896.         if ($request->query->get('audio')) {
  897.             /** @var ActivityRepository */
  898.             $activityRepo $this->getDoctrine();
  899.             if ($request->query->get('limit')) {
  900.                 /** @var Rdv[] */
  901.                 $rdvs $activityRepo
  902.                     ->getRepository(Rdv::class)
  903.                     ->findLastsOldRdvsWithLimit($request->query->get('limit'), $client->getId(), $request->query->get('audio'), new DateTime());
  904.                 $rdvResult = new ArrayCollection();
  905.             } else {
  906.                 /** @var Rdv[] */
  907.                 $rdvs $activityRepo
  908.                     ->getRepository(Rdv::class)
  909.                     ->findOldRdvs($client->getId(), $request->query->get('audio'), new DateTime());
  910.                 $rdvResult = new ArrayCollection();
  911.             }
  912.             foreach ($rdvs as $rdv) {
  913.                 /*if ($rdv->getIdEtat()->getId() != 1) {
  914.                     continue;
  915.                 }*/
  916.                 /** @var AudioMotif */
  917.                 $audioMotif $this->getDoctrine()
  918.                     ->getRepository(AudioMotif::class)
  919.                     ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  920.                 if (!$audioMotif) {
  921.                     continue;
  922.                 }
  923.                 $duration '';
  924.                 if (is_null($rdv->getDuration())) {
  925.                     $duration $audioMotif->getDuration();
  926.                 } else {
  927.                     $duration $rdv->getDuration();
  928.                 }
  929.                 $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  930.                 /** @var Rdv[] */
  931.                 $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  932.                     ->findAllReviewsCentre($rdvCentre->getId());
  933.                 $rdvItem = [
  934.                     "id" => $rdv->getId(),
  935.                     "motif_id" => $rdv->getIdMotif()->getId(),
  936.                     "duration" => $duration,
  937.                     "color" => $audioMotif->getColor(),
  938.                     "audio_id" => $rdv->getIdAudio()->getId(),
  939.                     "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  940.                     "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  941.                     "client_id" => $rdv->getIdClient()->getId(),
  942.                     "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() . " " $rdv->getIdProche()->getLastname() : $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname(),
  943.                     "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  944.                     "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  945.                     "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  946.                     "testclient" => $rdv->getTestClient() ? [
  947.                         "result" => $rdv->getTestClient()->getResultTonal(),
  948.                         "date" => $rdv->getTestClient()->getDate(),
  949.                         "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  950.                     ] : null,
  951.                     "name" => $rdvCentre->getName(),
  952.                     "phone" => $rdvCentre->getPhone(),
  953.                     "imgUrl" => $rdvCentre->getImgUrl(),
  954.                     "address" => $rdvCentre->getAddress(),
  955.                     "postale" => $rdvCentre->getPostale(),
  956.                     "city" => $rdvCentre->getCity(),
  957.                     "etat_id" => $rdvCentre->getId(),
  958.                     "averageRating" => $publicFunction->calculateRating($centreRdvs),
  959.                     "nbrReview" => count($centreRdvs),
  960.                     "acceptedCurrency" => "CB Chèque",
  961.                     "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  962.                     "note" => $rdv->getNote(),
  963.                     "comment" => $rdv->getComment(),
  964.                     "review" => $rdv->getReview(),
  965.                 ];
  966.                 $rdvResult->add($rdvItem);
  967.             }
  968.         }
  969.         if (count($rdvResult) > 0) {
  970.             return new Response(json_encode(([
  971.                 "rdv" => $rdvResult->toArray(),
  972.                 "status" => 200,
  973.             ])));
  974.         } else {
  975.             return new Response(json_encode(([
  976.                 "message" => "Aucun rendez-vous a venir!",
  977.                 'path' => 'src/Controller/RdvController.php',
  978.                 "status" => 404,
  979.             ])));
  980.         }
  981.     }
  982.     /**
  983.      * @Route("/rdvs/old/client/{id}/centre", name="getOldRdvsByClientIdForCentre", methods={"GET","HEAD"})
  984.      */
  985.     public function getOldRdvsByClientIdForCentre(Request $requestClient $clientPublicFunction $publicFunction)
  986.     {
  987.         if (!$request->query->get('token')) {
  988.             return new Response(json_encode([
  989.                 "message" => "Pas de token n'a été spécifié",
  990.                 "status" => 401,
  991.             ]), 401);
  992.         }
  993.         $entityManager $this->getDoctrine()->getManager();
  994.         /** @var Token */
  995.         $token $this->getDoctrine()
  996.             ->getRepository(Token::class)
  997.             ->findOneBy(['token' => $request->query->get('token')]);
  998.         if (!$token) {
  999.             return new Response(json_encode([
  1000.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1001.                 "status" => 404,
  1002.             ]), 404);
  1003.         }
  1004.         $audio $this->getDoctrine()
  1005.             ->getRepository(Audio::class)
  1006.             ->findOneBy(['id' => $request->query->get('audio')]);
  1007.         $audioCentre $this->getDoctrine()
  1008.             ->getRepository(AudioCentre::class)
  1009.             ->findOneBy(['id_audio' => $audio]);
  1010.         // get token age
  1011.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1012.         // if the token if older than 7 days
  1013.         if ($dateDiff->7) {
  1014.             $entityManager->remove($token);
  1015.             $entityManager->flush();
  1016.             return $this->json([
  1017.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1018.                 'path' => 'src/Controller/ClientController.php',
  1019.                 "status" => 401,
  1020.             ], 401);
  1021.         }
  1022.         if ($token->getIdClient()) {
  1023.             if ($client != $token->getIdClient()) {
  1024.                 return new Response(json_encode([
  1025.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  1026.                     "status" => 404,
  1027.                 ]), 404);
  1028.             }
  1029.         } else if ($token->getIdAudio()) {
  1030.             /** @var Token */
  1031.             if ($token->getIdAudio() != $audio) {
  1032.                 return new Response(json_encode([
  1033.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  1034.                     "status" => 404,
  1035.                 ]), 404);
  1036.             }
  1037.         } else {
  1038.             return new Response(json_encode([
  1039.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  1040.                 "status" => 404,
  1041.             ]), 404);
  1042.         }
  1043.         if ($request->query->get('audio')) {
  1044.             /** @var ActivityRepository */
  1045.             $activityRepo $this->getDoctrine();
  1046.             if ($request->query->get('limit')) {
  1047.                 /** @var Rdv[] */
  1048.                 $rdvs $activityRepo
  1049.                     ->getRepository(Rdv::class)
  1050.                     ->findLastsOldRdvCentresWithLimit($request->query->get('limit'), $client->getId(), $audioCentre->getIdCentre()->getId(), new DateTime());
  1051.                 $rdvResult = new ArrayCollection();
  1052.             } else {
  1053.                 /** @var Rdv[] */
  1054.                 $rdvs $activityRepo
  1055.                     ->getRepository(Rdv::class)
  1056.                     ->findOldRdvsByCentre($client->getId(), $audioCentre->getIdCentre()->getId(), new DateTime());
  1057.                 $rdvResult = new ArrayCollection();
  1058.             }
  1059.             //dd($rdvs);
  1060.             foreach ($rdvs as $rdv) {
  1061.                 // we comment this becoz it was just the validate , we implment other choice select
  1062.                 /* if ($rdv->getIdEtat()->getId() != 5) {
  1063.                     continue;
  1064.                 }*/
  1065.                 /** @var AudioMotif */
  1066.                 $audioMotif $this->getDoctrine()
  1067.                     ->getRepository(AudioMotif::class)
  1068.                     ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  1069.                 if (!$audioMotif) {
  1070.                     continue;
  1071.                 }
  1072.                 $duration '';
  1073.                 if (is_null($rdv->getDuration())) {
  1074.                     $duration $audioMotif->getDuration();
  1075.                 } else {
  1076.                     $duration $rdv->getDuration();
  1077.                 }
  1078.                 $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  1079.                 /** @var Rdv[] */
  1080.                 $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  1081.                     ->findAllReviewsCentre($rdvCentre->getId());
  1082.                 $rdvItem = [
  1083.                     "id" => $rdv->getId(),
  1084.                     "motif_id" => $rdv->getIdMotif()->getId(),
  1085.                     "duration" => $duration,
  1086.                     "color" => $audioMotif->getColor(),
  1087.                     "audio_id" => $rdv->getIdAudio()->getId(),
  1088.                     "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  1089.                     "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  1090.                     "client_id" => $rdv->getIdClient()->getId(),
  1091.                     "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() . " " $rdv->getIdProche()->getLastname() : $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname(),
  1092.                     "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  1093.                     "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  1094.                     "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  1095.                     "testclient" => $rdv->getTestClient() ? [
  1096.                         "result" => $rdv->getTestClient()->getResultTonal(),
  1097.                         "date" => $rdv->getTestClient()->getDate(),
  1098.                         "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  1099.                     ] : null,
  1100.                     "name" => $rdvCentre->getName(),
  1101.                     "phone" => $rdvCentre->getPhone(),
  1102.                     "imgUrl" => $rdvCentre->getImgUrl(),
  1103.                     "address" => $rdvCentre->getAddress(),
  1104.                     "postale" => $rdvCentre->getPostale(),
  1105.                     "city" => $rdvCentre->getCity(),
  1106.                     "etat_id" => $rdvCentre->getId(),
  1107.                     "averageRating" => $publicFunction->calculateRating($centreRdvs),
  1108.                     "nbrReview" => count($centreRdvs),
  1109.                     "acceptedCurrency" => "CB Chèque",
  1110.                     "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  1111.                     "note" => $rdv->getNote(),
  1112.                     "comment" => $rdv->getComment(),
  1113.                     "review" => $rdv->getReview(),
  1114.                     "status" => $rdv->getIdEtat()->getLibelle()
  1115.                 ];
  1116.                 $rdvResult->add($rdvItem);
  1117.             }
  1118.         }
  1119.         if (count($rdvResult) > 0) {
  1120.             return new Response(json_encode(([
  1121.                 "rdv" => $rdvResult->toArray(),
  1122.                 "status" => 200,
  1123.             ])));
  1124.         } else {
  1125.             return new Response(json_encode(([
  1126.                 "message" => "Aucun rendez-vous n'a été trouvé!",
  1127.                 'path' => 'src/Controller/RdvController.php',
  1128.                 "status" => 404,
  1129.             ])));
  1130.         }
  1131.     }
  1132.     private function getOpeningHours($centerId)
  1133.     {
  1134.         $center $this->getDoctrine()->getRepository(Centre::class)->find($centerId);
  1135.         $audioCentre $this->getDoctrine()->getRepository(AudioCentre::class)
  1136.             ->findOneBy(['id_centre' => $center->getId(), 'id_audio' => $center->getIdGerant()->getId()]);
  1137.         $schedule $audioCentre->getHoraire();
  1138.         $availableHours = [];
  1139.         if (isset($schedule['fixed'])) {
  1140.             foreach ($schedule['fixed'] as $day => $hours) {
  1141.                 $dayInFrench strtolower($day);
  1142.                 $slots = [];
  1143.                 foreach ($hours as $period) {
  1144.                     $start strtotime($period['open']);
  1145.                     $end strtotime($period['close']);
  1146.                     while ($start $end) {
  1147.                         $slots[] = date('H:i'$start);
  1148.                         $start strtotime('+30 minutes'$start);
  1149.                     }
  1150.                 }
  1151.                 $availableHours[$dayInFrench] = $slots;
  1152.             }
  1153.         }
  1154.         if (isset($schedule['exceptionalOpened'])) {
  1155.             foreach ($schedule['exceptionalOpened'] as $exception) {
  1156.                 $dayOfWeek strtolower(date('l'strtotime($exception['open'])));
  1157.                 $start strtotime($exception['open']);
  1158.                 $end strtotime($exception['close']);
  1159.                 $exceptionSlots = [];
  1160.                 while ($start $end) {
  1161.                     $exceptionSlots[] = date('H:i'$start);
  1162.                     $start strtotime('+30 minutes'$start);
  1163.                 }
  1164.                 $availableHours[$dayOfWeek] = array_merge(
  1165.                     $availableHours[$dayOfWeek] ?? [],
  1166.                     $exceptionSlots
  1167.                 );
  1168.             }
  1169.         }
  1170.         if (isset($schedule['exceptionalClosed'])) {
  1171.             foreach ($schedule['exceptionalClosed'] as $exception) {
  1172.                 $dayOfWeek strtolower(date('l'strtotime($exception['open'])));
  1173.                 unset($availableHours[$dayOfWeek]);
  1174.             }
  1175.         }
  1176.         return $availableHours;
  1177.     }
  1178.     private function getBookedSlotsForDate($centerId$date)
  1179.     {
  1180.         $bookedSlots $this->getDoctrine()
  1181.             ->getRepository(Rdv::class)
  1182.             ->getBookedSlotsForDate($centerId$date);
  1183.         return $bookedSlots;
  1184.     }
  1185.     private function getAvailableSlotsForDate($openingHours$centerId$date)
  1186.     {
  1187.         $dayOfWeek date('l'strtotime($date));
  1188.         $dayInFrench $this->convertDayToFrench($dayOfWeek);
  1189.         if (!$dayInFrench) {
  1190.             throw new \Exception("Invalid day of the week: $dayOfWeek");
  1191.         }
  1192.         $slots $openingHours[$dayInFrench] ?? [];
  1193.         $bookedSlots $this->getBookedSlotsForDate($centerId$date);
  1194.         $bookedTimes = [];
  1195.         foreach ($bookedSlots as $bookedSlot) {
  1196.             $startTime $bookedSlot['date'];
  1197.             $duration $bookedSlot['duration'];
  1198.             $endTime = (clone $startTime)->modify("+$duration minutes");
  1199.             $bookedTimes[] = ['start' => $startTime'end' => $endTime];
  1200.         }
  1201.         $availableSlots = [];
  1202.         foreach ($slots as $slot) {
  1203.             $slotTime \DateTime::createFromFormat('H:i'$slot);
  1204.             $slotTime->setDate(date('Y'strtotime($date)), date('m'strtotime($date)), date('d'strtotime($date)));
  1205.             if (!$slotTime) {
  1206.                 continue;
  1207.             }
  1208.             $isAvailable true;
  1209.             foreach ($bookedTimes as $bookedTime) {
  1210.                 if ($slotTime >= $bookedTime['start'] && $slotTime $bookedTime['end']) {
  1211.                     $isAvailable false;
  1212.                     break;
  1213.                 }
  1214.             }
  1215.             if ($isAvailable) {
  1216.                 $availableSlots[] = $slot;
  1217.             }
  1218.         }
  1219.         return $availableSlots;
  1220.     }
  1221.     private function convertDayToFrench($englishDay)
  1222.     {
  1223.         $daysMap = [
  1224.             'monday' => 'lundi',
  1225.             'tuesday' => 'mardi',
  1226.             'wednesday' => 'mercredi',
  1227.             'thursday' => 'jeudi',
  1228.             'friday' => 'vendredi',
  1229.             'saturday' => 'samedi',
  1230.             'sunday' => 'dimanche'
  1231.         ];
  1232.         return $daysMap[strtolower($englishDay)] ?? null;
  1233.     }
  1234.     /**
  1235.      * @Route("/audio/{id}/rdvs/", name="getAudioRdvs", methods={"GET","HEAD"})
  1236.      */
  1237.     public function getAudioRdvs(Request $requestAudio $audio)
  1238.     {
  1239.         if (!$request->query->get('token')) {
  1240.             return new Response(json_encode([
  1241.                 "message" => "Pas de token n'a été spécifié",
  1242.                 "status" => 401,
  1243.             ]), 401);
  1244.         }
  1245.         $entityManager $this->getDoctrine()->getManager();
  1246.         /** @var Token */
  1247.         $token $this->getDoctrine()
  1248.             ->getRepository(Token::class)
  1249.             ->findOneBy(['token' => $request->query->get('token')]);
  1250.         if (!$token) {
  1251.             return new Response(json_encode([
  1252.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1253.                 "status" => 404,
  1254.             ]), 404);
  1255.         }
  1256.         // get token age
  1257.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1258.         // if the token if older than 7 days
  1259.         if ($dateDiff->7) {
  1260.             $entityManager->remove($token);
  1261.             $entityManager->flush();
  1262.             return $this->json([
  1263.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1264.                 'path' => 'src/Controller/ClientController.php',
  1265.                 "status" => 401,
  1266.             ], 401);
  1267.         }
  1268.         if ($audio != $token->getIdAudio()) {
  1269.             return new Response(json_encode([
  1270.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  1271.                 "status" => 404,
  1272.             ]), 404);
  1273.         }
  1274.         $centre = (int)$request->query->get('centre');
  1275.         if (($request->query->get('debut')) && ($request->query->get('fin'))) {
  1276.             $rdvs $this->getDoctrine()
  1277.                 ->getRepository(Rdv::class)
  1278.                 ->findBetweenDate(
  1279.                     $audio->getId(),
  1280.                     new DateTime($request->query->get('debut')),
  1281.                     new DateTime($request->query->get('fin')),
  1282.                     $centre // Le centre est maintenant un entier
  1283.                 );
  1284.         } else {
  1285.             $rdvs $this->getDoctrine()
  1286.                 ->getRepository(Rdv::class)
  1287.                 ->findBy(['id_audio' => $audio->getId()]);
  1288.         }
  1289.         $rdvResult = new ArrayCollection();
  1290.         $centerId $request->query->get('centre');
  1291.         // $openingHours = $this->getOpeningHours($centerId); 
  1292.         $centerId $request->query->get('centre');
  1293.         $dateCache = new \DateTime();
  1294.         $openingHours $this->cache->get('centre_' $centerId '_horaires_' $dateCache->format('Y-m-d'), function (ItemInterface $item) use ($centerId$dateCache) {
  1295.             $item->expiresAfter(7200);
  1296.             return $this->getOpeningHours($centerId);
  1297.         });
  1298.         //dd($openingHours);
  1299.         foreach ($rdvs as $rdv) {
  1300.             if ($rdv->getIdEtat()->getId() != null) {
  1301.                 if ($rdv->getIsAbsence() != 1) {
  1302.                     /** @var AudioMotif */
  1303.                     $audioMotif $this->getDoctrine()
  1304.                         ->getRepository(AudioMotif::class)
  1305.                         ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $audio->getId()]);
  1306.                     if (!isset($audioMotif)) {
  1307.                         continue;
  1308.                     }
  1309.                     $motif $this->getDoctrine()
  1310.                         ->getRepository(Motif::class)
  1311.                         ->findOneBy(['id' => $rdv->getIdMotif()->getId()]);
  1312.                     $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  1313.                     if ($rdv->getIdClientTemp()) {
  1314.                         $confiance "";
  1315.                     } else {
  1316.                         $confiance $client->getIdPersonneConfiance() ? $client->getIdPersonneConfiance()->getId() : null;
  1317.                     }
  1318.                 }
  1319.                 $duration '';
  1320.                 if (is_null($rdv->getDuration())) {
  1321.                     $duration $audioMotif->getDuration();
  1322.                 } else {
  1323.                     $duration $rdv->getDuration();
  1324.                 }
  1325.                 $dateFin = new DateTime($rdv->getDate()->format('Y-m-d\TH:i:s'));
  1326.                 $dateFin $dateFin->add(new DateInterval("PT" $duration "M"));
  1327.                 if ($rdv->getIdClientTemp()) {
  1328.                     $findNextRdv $this->getDoctrine()
  1329.                         ->getRepository(Rdv::class)
  1330.                         ->findBy([
  1331.                             "id_client_temp" => $rdv->getIdClientTemp(),
  1332.                             "id_motif" => ['106''107''108''109']
  1333.                         ]);
  1334.                 } else {
  1335.                     $findNextRdv $this->getDoctrine()
  1336.                         ->getRepository(Rdv::class)
  1337.                         ->findBy([
  1338.                             "id_client_temp" => $rdv->getIdClient(),
  1339.                             "id_motif" => ['106''107''108''109']
  1340.                         ]);
  1341.                 }
  1342.                 $finalRdv null;
  1343.                 /*if ($rdv->getRdvParent()) {
  1344.     $finalRdv = $this->getDoctrine()
  1345.         ->getRepository(Rdv::class)
  1346.         ->find($rdv->getRdvParent());
  1347. }*/
  1348.                 //if($client->getClientDevices())
  1349.                 //{
  1350.                 //if ($client->getClientDevices()->first()) {
  1351.                 /*$nextRdv = $this->getDoctrine()
  1352.                  ->getRepository(Rdv::class)
  1353.                  ->find($finalRdv->getClientDevice()->getRdv()->getId());*/
  1354.                 //  }
  1355.                 //}
  1356.                 if ($rdv->getIsAbsence() != 1) {
  1357.                     if ($rdv->getIdClientTemp()) {
  1358.                         $nextRdvs $this->getDoctrine()
  1359.                             ->getRepository(Rdv::class)
  1360.                             ->findBy([
  1361.                                 "id_client_temp" => $client,
  1362.                                 "id_motif" => ['106''107''108''109']
  1363.                             ]);
  1364.                     } else {
  1365.                         $nextRdvs $this->getDoctrine()
  1366.                             ->getRepository(Rdv::class)
  1367.                             ->findBy([
  1368.                                 "id_client" => $client,
  1369.                                 "id_motif" => ['106''107''108''109']
  1370.                             ]);
  1371.                     }
  1372.                     if ($client->getClientDevices()) {
  1373.                         if ($client->getClientDevices()->first()) {
  1374.                             if (empty($nextRdvs)) {
  1375.                                 $isNextRdv false;
  1376.                                 $initialRdvDate $rdv->getDate();
  1377.                                 $availableSlots = [
  1378.                                     'Suivi de l’essai' => $this->findFirstAvailableSlot($centerId$initialRdvDate7),
  1379.                                     'Confirmation de l’essai' => $this->findFirstAvailableSlot($centerId$initialRdvDate14),
  1380.                                     'Validation de l’appareillage' => $this->findFirstAvailableSlot($centerId$initialRdvDate21),
  1381.                                     'Facturation de l’appareillage' => $this->findFirstAvailableSlot($centerId$initialRdvDate30),
  1382.                                     'duration' => "30"
  1383.                                 ];
  1384.                                 $mappedNextRdvs = [
  1385.                                     'Suivi de l’essai' => $this->findAvailableDay($centerId$initialRdvDate7),
  1386.                                     'Confirmation de l’essai' => $this->findAvailableDay($centerId$initialRdvDate14),
  1387.                                     'Validation de l’appareillage' => $this->findAvailableDay($centerId$initialRdvDate21),
  1388.                                     'Facturation de l’appareillage' => $this->findAvailableDay($centerId$initialRdvDate30),
  1389.                                     'duration' => "30"
  1390.                                 ];
  1391.                             } else {
  1392.                                 $isNextRdv true;
  1393.                                 $initialRdvDate $rdv->getDate();
  1394.                                 // Available slots for each follow-up date
  1395.                                 $availableSlots = [];
  1396.                                 if (isset($nextRdvs[0])) {
  1397.                                     $availableSlots['Suivi de l’essai'] = $this->getAvailableSlotsForDate(
  1398.                                         $openingHours,
  1399.                                         $centerId,
  1400.                                         $nextRdvs[0]->getDate()->format('Y-m-d')
  1401.                                     );
  1402.                                 }
  1403.                                 if (isset($nextRdvs[1])) {
  1404.                                     $availableSlots['Confirmation de l’essai'] = $this->getAvailableSlotsForDate(
  1405.                                         $openingHours,
  1406.                                         $centerId,
  1407.                                         $nextRdvs[1]->getDate()->format('Y-m-d')
  1408.                                     );
  1409.                                 }
  1410.                                 if (isset($nextRdvs[2])) {
  1411.                                     $availableSlots['Validation de l’appareillage'] = $this->getAvailableSlotsForDate(
  1412.                                         $openingHours,
  1413.                                         $centerId,
  1414.                                         $nextRdvs[2]->getDate()->format('Y-m-d')
  1415.                                     );
  1416.                                 }
  1417.                                 if (isset($nextRdvs[3])) {
  1418.                                     $availableSlots['Facturation de l’appareillage'] = $this->getAvailableSlotsForDate(
  1419.                                         $openingHours,
  1420.                                         $centerId,
  1421.                                         $nextRdvs[3]->getDate()->format('Y-m-d')
  1422.                                     );
  1423.                                 }
  1424.                                 $mappedNextRdvs array_map(function ($rdv) {
  1425.                                     return [
  1426.                                         'id' => $rdv->getId(),
  1427.                                         'date' => $rdv->getDate()->format('d-m-Y'),
  1428.                                         'hours' => $rdv->getDate()->format('H:i'),
  1429.                                         'duration' => $rdv->getDuration(),
  1430.                                         "motif_id" => $rdv->getIdMotif()->getId(),
  1431.                                         "motif_titre" => $rdv->getIdMotif()->getTitre(),
  1432.                                     ];
  1433.                                 }, $nextRdvs);
  1434.                             }
  1435.                         }
  1436.                     }
  1437.                     $rdvItem = [
  1438.                         "id" => $rdv->getId(),
  1439.                         "motif_id" => $rdv->getIdMotif()->getId(),
  1440.                         "motif_titre" => $motif->getTitre(),
  1441.                         "duration" => $duration,
  1442.                         "color" => $audioMotif->getColor(),
  1443.                         "audio_id" => $rdv->getIdAudio()->getId(),
  1444.                         "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  1445.                         "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  1446.                         "client_id" => $client->getId(),
  1447.                         "isClient" => ($client instanceof Client) ? 0,
  1448.                         "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() : $client->getName(),
  1449.                         "client_lastname" => $rdv->getIdProche() ? $rdv->getIdProche()->getLastname() : $client->getLastname(),
  1450.                         "client_mail" => $client->getMail(),
  1451.                         "client_tel" => $client->getPhone(),
  1452.                         "client_fixe" => $client->getPhoneFixe(),
  1453.                         "confiance" =>  $confiance,
  1454.                         "client_birthday" => $client->getBirthdate() ? $client->getBirthdate()->format("Y-m-d") : null,
  1455.                         "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  1456.                         "centre_id" => $rdv->getIdCentre()->getId(),
  1457.                         "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  1458.                         "testclient" => $rdv->getTestClient() ? [
  1459.                             "result" => $rdv->getTestClient()->getResultTonal(),
  1460.                             "date" => $rdv->getTestClient()->getDate(),
  1461.                             "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  1462.                         ] : null,
  1463.                         "name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : $rdv->getIdLieu()->getName(),
  1464.                         "centerName" => $rdv->getIdCentre()->getName(),
  1465.                         "phone" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getPhone() : $rdv->getIdLieu()->getPhone(),
  1466.                         "etat_id" => $rdv->getIdEtat()->getId(),
  1467.                         "clientEtatId" => $client->getClientStatus() ? $client->getClientStatus()->getId() : 0,
  1468.                         "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  1469.                         "dateFin" => $dateFin->format('Y-m-d\TH:i:s'),
  1470.                         "comment" => $rdv->getComment(),
  1471.                         "note" => $rdv->getNote(),
  1472.                         "isTemp" => $rdv->getIdClientTemp() ? 0,
  1473.                         "isAbsence" => $rdv->getIsAbsence(),
  1474.                         "device" => $client->getClientDevices()->first() ? [
  1475.                             "isDevice" => true,
  1476.                             "isNextRdv" => $isNextRdv,
  1477.                             "deviceID" => $client->getClientDevices()->first()->getDevice()->getId(),
  1478.                             "clientDeviceID" => $client->getClientDevices()->first()->getId(),
  1479.                             "deviceModel" => $client->getClientDevices()->first()->getDevice()->getModel(),
  1480.                             "settingDeviceId" => $client->getClientDevices()->first()->getSettingDevice()->getSlug(),
  1481.                             "settingName" => $client->getClientDevices()->first()->getSettingDevice()->getName(),
  1482.                             "settingSlug" => $client->getClientDevices()->first()->getSettingDevice()->getSlug(),
  1483.                             "nextRdvs" => $mappedNextRdvs,
  1484.                             "available_slots" => $availableSlots
  1485.                         ] : [
  1486.                             "isDevice" => false
  1487.                         ]
  1488.                     ];
  1489.                 } else {
  1490.                     // $clientDevice = $client->getClientDevices()->first();
  1491.                     $rdvItem = [
  1492.                         "id" => $rdv->getId(),
  1493.                         "duration" => $duration,
  1494.                         "color" => $rdv->getColor() ? $rdv->getColor() . '66' '#ffb2b266',
  1495.                         "audio_id" => $rdv->getIdAudio()->getId(),
  1496.                         "client_id" =>  "",
  1497.                         "isClient" => false,
  1498.                         "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  1499.                         "centre_id" => $rdv->getIdCentre()->getId(),
  1500.                         "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  1501.                         "name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : $rdv->getIdLieu()->getName(),
  1502.                         "phone" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getPhone() : $rdv->getIdLieu()->getPhone(),
  1503.                         "etat_id" => $rdv->getIdEtat()->getId(),
  1504.                         "clientEtatId" => "",
  1505.                         "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  1506.                         "dateFin" => $dateFin->format('Y-m-d\TH:i:s'),
  1507.                         "note" => $rdv->getNote(),
  1508.                         "device" => "",
  1509.                         "centerName" => $rdv->getIdCentre()->getName(),
  1510.                         "isTemp" => $rdv->getIdClientTemp() ? 0,
  1511.                         "isAbsence" => $rdv->getIsAbsence(),
  1512.                         "motif_titre" => $rdv->getMotifAbsence() ? $rdv->getMotifAbsence() : "Absence",
  1513.                     ];
  1514.                 }
  1515.                 //  if ($rdv->getDate() >= new DateTime())
  1516.                 $rdvResult->add($rdvItem);
  1517.             }
  1518.         }
  1519.         $startDate = new \DateTime('2024-02-20');
  1520.         $rdvs $this->rdvRepo->findRdvsNeedingReminderByAudio($startDate$audio->getId());
  1521.         //dd($audio->getId());
  1522.         $reminders = [];
  1523.         //dd($rdvs);
  1524.         foreach ($rdvs as $rdv) {
  1525.             $info $this->checkRdvReminder($rdv);
  1526.             if ($info !== null) {
  1527.                 $reminders[] = $info;
  1528.             }
  1529.         }
  1530.         //dd($reminders);
  1531.         if (count($rdvResult) > 0) {
  1532.             return new Response(json_encode(([
  1533.                 "content" => $rdvResult->toArray(),
  1534.                 "status" => 200,
  1535.                 "reminders" => $reminders,
  1536.                 "datefin" => $dateFin
  1537.             ])));
  1538.         } else {
  1539.             $rdvItem = [];
  1540.             //$rdvResult->add($rdvItem);
  1541.             return new Response(json_encode(([
  1542.                 "content" => $rdvResult->toArray(),
  1543.                 "message" => "Aucun rendez-vous n'a été trouvé!",
  1544.                 'path' => 'src/Controller/RdvController.php',
  1545.                 "reminders" => $reminders,
  1546.                 "status" => 404,
  1547.             ])));
  1548.         }
  1549.     }
  1550.     private function findAvailableDay(int $centerId\DateTime $initialRdvDateint $offset): string
  1551.     {
  1552.         $currentDate = (clone $initialRdvDate)->modify("+{$offset} days");
  1553.         while (true) {
  1554.             $formattedDate $currentDate->format('Y-m-d');
  1555.             $slots $this->getAvailableSlotsForDate(
  1556.                 $this->getOpeningHoursList($centerId$formattedDate),
  1557.                 $centerId,
  1558.                 $formattedDate
  1559.             );
  1560.             if (!empty($slots)) {
  1561.                 return $formattedDate;
  1562.             }
  1563.             $currentDate->modify('+1 day');
  1564.         }
  1565.     }
  1566.     private function findFirstAvailableSlot(int $centerId\DateTime $initialRdvDateint $offset): array
  1567.     {
  1568.         $currentDate = (clone $initialRdvDate)->modify("+{$offset} days");
  1569.         while (true) {
  1570.             $formattedDate $currentDate->format('Y-m-d');
  1571.             $slots $this->getAvailableSlotsForDate(
  1572.                 $this->getOpeningHoursList($centerId$formattedDate),
  1573.                 $centerId,
  1574.                 $formattedDate
  1575.             );
  1576.             if (!empty($slots)) {
  1577.                 return $slots;
  1578.             }
  1579.             $currentDate->modify('+1 day');
  1580.         }
  1581.     }
  1582.     private function getOpeningHoursList($centerId$date)
  1583.     {
  1584.         $center $this->getDoctrine()->getRepository(Centre::class)->find($centerId);
  1585.         $audioCentre $this->getDoctrine()->getRepository(AudioCentre::class)
  1586.             ->findOneBy(['id_centre' => $center->getId(), 'id_audio' => $center->getIdGerant()->getId()]);
  1587.         $schedule $audioCentre->getHoraire();
  1588.         $availableHours = [];
  1589.         $holidayDates = [
  1590.             'JourdelAn' => '01-01',
  1591.             'LundidePâques' => '21-04',
  1592.             'FêteduTravail' => '01-05',
  1593.             'Victoire1945' => '08-05',
  1594.             'Ascension' => '29-05',
  1595.             'LundidePentecôte' => '09-06',
  1596.             'FêteNationale' => '14-07',
  1597.             'Assomption' => '15-08',
  1598.             'Toussaint' => '01-11',
  1599.             'Armistice1918' => '11-11',
  1600.             'Noël' => '25-12',
  1601.         ];
  1602.         $holidays $center->getHorairesHoliday();
  1603.         $requestDate date('d-m'strtotime($date));
  1604.         $englishToFrenchDays = [
  1605.             'monday' => 'lundi',
  1606.             'tuesday' => 'mardi',
  1607.             'wednesday' => 'mercredi',
  1608.             'thursday' => 'jeudi',
  1609.             'friday' => 'vendredi',
  1610.             'saturday' => 'samedi',
  1611.             'sunday' => 'dimanche',
  1612.         ];
  1613.         $dayOfWeek strtolower(date('l'strtotime($date)));
  1614.         $dayInFrench $englishToFrenchDays[$dayOfWeek];
  1615.         if (isset($schedule['fixed'])) {
  1616.             foreach ($schedule['fixed'] as $day => $hours) {
  1617.                 $dayKey strtolower($day);
  1618.                 $slots = [];
  1619.                 foreach ($hours as $period) {
  1620.                     $start strtotime($period['open']);
  1621.                     $end strtotime($period['close']);
  1622.                     while ($start $end) {
  1623.                         $slots[] = date('H:i'$start);
  1624.                         $start strtotime('+30 minutes'$start);
  1625.                     }
  1626.                 }
  1627.                 $availableHours[$dayKey] = $slots;
  1628.             }
  1629.         }
  1630.         foreach ($holidays['fixed'] as $holiday => $hours) {
  1631.             if (isset($holidayDates[$holiday]) && $holidayDates[$holiday] === $requestDate) {
  1632.                 $holidaySlots = [];
  1633.                 if (!empty($hours)) {
  1634.                     foreach ($hours as $period) {
  1635.                         $start strtotime($period['open']);
  1636.                         $end strtotime($period['close']);
  1637.                         while ($start $end) {
  1638.                             $holidaySlots[] = date('H:i'$start);
  1639.                             $start strtotime('+30 minutes'$start);
  1640.                         }
  1641.                     }
  1642.                     $availableHours[$dayInFrench] = $holidaySlots;
  1643.                 } else {
  1644.                     $availableHours[$dayInFrench] = [];
  1645.                 }
  1646.                 break;
  1647.             }
  1648.         }
  1649.         return $availableHours;
  1650.     }
  1651.     /**
  1652.      * @Route("/audio/{id}/rdvsTest/", name="getAudioRdvsTest", methods={"GET","HEAD"})
  1653.      */
  1654.     public function getAudioRdvsTest(Request $requestAudio $audio)
  1655.     {
  1656.         if (!$request->query->get('token')) {
  1657.             return new Response(json_encode([
  1658.                 "message" => "Pas de token n'a été spécifié",
  1659.                 "status" => 401,
  1660.             ]), 401);
  1661.         }
  1662.         $entityManager $this->getDoctrine()->getManager();
  1663.         /** @var Token */
  1664.         $token $this->getDoctrine()
  1665.             ->getRepository(Token::class)
  1666.             ->findOneBy(['token' => $request->query->get('token')]);
  1667.         if (!$token) {
  1668.             return new Response(json_encode([
  1669.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1670.                 "status" => 404,
  1671.             ]), 404);
  1672.         }
  1673.         // get token age
  1674.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1675.         // if the token if older than 7 days
  1676.         if ($dateDiff->7) {
  1677.             $entityManager->remove($token);
  1678.             $entityManager->flush();
  1679.             return $this->json([
  1680.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1681.                 'path' => 'src/Controller/ClientController.php',
  1682.                 "status" => 401,
  1683.             ], 401);
  1684.         }
  1685.         if ($audio != $token->getIdAudio()) {
  1686.             return new Response(json_encode([
  1687.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  1688.                 "status" => 404,
  1689.             ]), 404);
  1690.         }
  1691.         /** @var Rdv[] */
  1692.         if (($request->query->get('debut')) && ($request->query->get('fin'))) {
  1693.             $rdvs $this->getDoctrine()
  1694.                 ->getRepository(Rdv::class)
  1695.                 ->findBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1696.         } else {
  1697.             $rdvs $this->getDoctrine()
  1698.                 ->getRepository(Rdv::class)
  1699.                 ->findBy(['id_audio' => $audio->getId()]);
  1700.         }
  1701.         $rdvResult = new ArrayCollection();
  1702.         foreach ($rdvs as $rdv) {
  1703.             if ($rdv->getIdEtat()->getId() != null) {
  1704.                 /** @var AudioMotif */
  1705.                 $audioMotif $this->getDoctrine()
  1706.                     ->getRepository(AudioMotif::class)
  1707.                     ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $audio->getId()]);
  1708.                 if (!isset($audioMotif)) {
  1709.                     continue;
  1710.                 }
  1711.                 $motif $this->getDoctrine()
  1712.                     ->getRepository(Motif::class)
  1713.                     ->findOneBy(['id' => $rdv->getIdMotif()->getId()]);
  1714.                 $dateFin = new DateTime($rdv->getDate()->format('Y-m-d H:i:s'));
  1715.                 $dateFin $dateFin->add(new DateInterval("PT" $audioMotif->getDuration() . "M"));
  1716.                 $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  1717.                 $name $rdv->getIdProche() ? $rdv->getIdProche()->getName() : $client->getName();
  1718.                 $lastName $rdv->getIdProche() ? $rdv->getIdProche()->getLastname() : $client->getLastname();
  1719.                 $rdvItem = [
  1720.                     "id" => $rdv->getId(),
  1721.                     "title" => $lastName ' ' $name,
  1722.                     "start" => $rdv->getDate()->format('Y-m-d H:i:s'),
  1723.                     "end"   => $dateFin->format('Y-m-d H:i:s'),
  1724.                     "backgroundColor" => $audioMotif->getColor(),
  1725.                     "editable" => true,
  1726.                     "durationEditable" => false,
  1727.                     "resourceEditable" => true,
  1728.                     "cache" => false,
  1729.                     "motif_id" => $rdv->getIdMotif()->getId(),
  1730.                     "motif" => $motif->getTitre(),
  1731.                     "duree" => $audioMotif->getDuration(),
  1732.                     "color" => $audioMotif->getColor(),
  1733.                     "color_motif" => $audioMotif->getColor(),
  1734.                     "client_id" => $client->getId(),
  1735.                     "clientName" => $name,
  1736.                     "clientLastName" => $lastName,
  1737.                     "mail" => $client->getMail(),
  1738.                     "telephone" => $client->getPhone(),
  1739.                     "birthday" => $client->getBirthdate(),
  1740.                     "etat_id" => $rdv->getIdEtat()->getId(),
  1741.                     "dateDeb" => $rdv->getDate()->format('Y-m-d H:i:s'),
  1742.                     "dateFin" => $dateFin->format('Y-m-d H:i:s'),
  1743.                     "commentaire" => $rdv->getNote(),
  1744.                     "event_title" => "<b>" $lastName "</b> " $name,
  1745.                 ];
  1746.                 //  if ($rdv->getDate() >= new DateTime())
  1747.                 $rdvResult->add($rdvItem);
  1748.             }
  1749.         }
  1750.         if (count($rdvResult) > 0) {
  1751.             return new Response(json_encode(
  1752.                 $rdvResult->toArray(),
  1753.             ));
  1754.         } else {
  1755.             $rdvItem = [];
  1756.             //$rdvResult->add($rdvItem);
  1757.             return new Response(json_encode(
  1758.                 $rdvResult->toArray(),
  1759.             ));
  1760.         }
  1761.     }
  1762.     /**
  1763.      * @Route("/audio/{id}/rdvs/count", name="getCountAudioRdvs", methods={"GET","HEAD"})
  1764.      */
  1765.     public function getCountAudioRdvs(Request $requestAudio $audio)
  1766.     {
  1767.         if (!$request->query->get('token')) {
  1768.             return new Response(json_encode([
  1769.                 "message" => "Pas de token n'a été spécifié",
  1770.                 "status" => 401,
  1771.             ]), 401);
  1772.         }
  1773.         $entityManager $this->getDoctrine()->getManager();
  1774.         /** @var Token */
  1775.         $token $this->getDoctrine()
  1776.             ->getRepository(Token::class)
  1777.             ->findOneBy(['token' => $request->query->get('token')]);
  1778.         if (!$token) {
  1779.             return new Response(json_encode([
  1780.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1781.                 "status" => 404,
  1782.             ]), 404);
  1783.         }
  1784.         // get token age
  1785.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1786.         // if the token if older than 7 days
  1787.         if ($dateDiff->7) {
  1788.             $entityManager->remove($token);
  1789.             $entityManager->flush();
  1790.             return $this->json([
  1791.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1792.                 'path' => 'src/Controller/ClientController.php',
  1793.                 "status" => 401,
  1794.             ], 401);
  1795.         }
  1796.         if ($audio != $token->getIdAudio()) {
  1797.             return new Response(json_encode([
  1798.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  1799.                 "status" => 404,
  1800.             ]), 404);
  1801.         }
  1802.         /** @var Rdv[] */
  1803.         $rdvs $this->getDoctrine()
  1804.             ->getRepository(Rdv::class)
  1805.             ->findBy(['id_audio' => $audio->getId()]);
  1806.         return new Response(json_encode(([
  1807.             "content" => count($rdvs),
  1808.             "status" => 200,
  1809.         ])));
  1810.     }
  1811.     /**
  1812.      * @Route("/audio/{id}/rdvsDate/count", name="getCountAudioRdvsBetweenDate", methods={"GET","HEAD"})
  1813.      */
  1814.     public function getCountAudioRdvsBetweenDate(Request $requestAudio $audio)
  1815.     {
  1816.         if (!$request->query->get('token')) {
  1817.             return new Response(json_encode([
  1818.                 "message" => "Pas de token n'a été spécifié",
  1819.                 "status" => 401,
  1820.             ]), 401);
  1821.         }
  1822.         $entityManager $this->getDoctrine()->getManager();
  1823.         /** @var Token */
  1824.         $token $this->getDoctrine()
  1825.             ->getRepository(Token::class)
  1826.             ->findOneBy(['token' => $request->query->get('token')]);
  1827.         if (!$token) {
  1828.             return new Response(json_encode([
  1829.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1830.                 "status" => 404,
  1831.             ]), 404);
  1832.         }
  1833.         // get token age
  1834.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1835.         // if the token if older than 7 days
  1836.         if ($dateDiff->7) {
  1837.             $entityManager->remove($token);
  1838.             $entityManager->flush();
  1839.             return $this->json([
  1840.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1841.                 'path' => 'src/Controller/ClientController.php',
  1842.                 "status" => 401,
  1843.             ], 401);
  1844.         }
  1845.         if ($audio != $token->getIdAudio()) {
  1846.             return new Response(json_encode([
  1847.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  1848.                 "status" => 404,
  1849.             ]), 404);
  1850.         }
  1851.         /** @var Rdv[] */
  1852.         $allRdvs $this->getDoctrine()
  1853.             ->getRepository(Rdv::class)
  1854.             ->findOnlyRdvAudioBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1855.         /** @var Rdv[] */
  1856.         $rdvs $this->getDoctrine()
  1857.             ->getRepository(Rdv::class)
  1858.             ->findOnlyRdvAudioWithoutTestBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1859.         /** @var Rdv[] */
  1860.         $rdvsWithTest $this->getDoctrine()
  1861.             ->getRepository(Rdv::class)
  1862.             ->findOnlyRdvAudioWithTestBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1863.         /** @var Rdv[] */
  1864.         $allRdvsCanceled $this->getDoctrine()
  1865.             ->getRepository(Rdv::class)
  1866.             ->findCanceledRdvAudioBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1867.         /** @var Rdv[] */
  1868.         $allRdvsCanceledCentre $this->getDoctrine()
  1869.             ->getRepository(Rdv::class)
  1870.             ->findCanceledRdvCentreBetweenDate(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1871.         /** @var Rdv[] */
  1872.         $rdvsClosed $this->getDoctrine()
  1873.             ->getRepository(Rdv::class)
  1874.             ->findClosedRdvBetweenDate(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1875.         $myLead 0;
  1876.         $rdvsCanceled $this->getDoctrine()
  1877.             ->getRepository(Rdv::class)
  1878.             ->findCanceledRdvAudioBetweenDateWithoutTest($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1879.         foreach ($rdvsCanceled as $rdvc) {
  1880.             if (!is_null($rdvc->getIdClient())) {
  1881.                 $rdvClient $this->getDoctrine()
  1882.                     ->getRepository(Rdv::class)
  1883.                     ->findRDVLeadByClient(new DateTime($request->query->get('debut')), $request->query->get('centre'), $rdvc->getIdClient()->getID());
  1884.                 if (count($rdvClient) == 0) {
  1885.                     $myLead $myLead 1;
  1886.                 }
  1887.             }
  1888.         }
  1889.         $myLeadAdvanced 0;
  1890.         $rdvsCanceledA $this->getDoctrine()
  1891.             ->getRepository(Rdv::class)
  1892.             ->findCanceledRdvAudioBetweenDateWithTest($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1893.         foreach ($rdvsCanceledA as $rdvc) {
  1894.             if (!is_null($rdvc->getIdClient())) {
  1895.                 $rdvClient $this->getDoctrine()
  1896.                     ->getRepository(Rdv::class)
  1897.                     ->findRDVLeadByClient(new DateTime($request->query->get('debut')), $request->query->get('centre'), $rdvc->getIdClient()->getID());
  1898.                 if (count($rdvClient) == 0) {
  1899.                     $myLeadAdvanced $myLeadAdvanced 1;
  1900.                 }
  1901.             }
  1902.         }
  1903.         /**** MY RDV Centre****/
  1904.         $myrdvCentre 0;
  1905.         $rdvs $this->getDoctrine()
  1906.             ->getRepository(Rdv::class)
  1907.             ->findRDVCentreBetweenDateWithoutTest(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1908.         $myrdvCentre count($rdvs);
  1909.         /**** MY RDV ADVANCED ****/
  1910.         $myRdvAdvancedCentre 0;
  1911.         $rdvsA $this->getDoctrine()
  1912.             ->getRepository(Rdv::class)
  1913.             ->findRDVCentreBetweenDateWithTestId(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1914.         $myRdvAdvancedCentre count($rdvsA);
  1915.         /**** FIRST RDV BY MOTIF PREMIER RDV ****/
  1916.         $myFirstRdv 0;
  1917.         $rdvsFirst $this->getDoctrine()
  1918.             ->getRepository(Rdv::class)
  1919.             ->findFirstRdv(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1920.         $myFirstRdv count($rdvsFirst);
  1921.         /****  RDV BY RECHERCHE RESULT VIA MYAUDIO ****/
  1922.         $myAudioRdv 0;
  1923.         $audioRdv $this->getDoctrine()
  1924.             ->getRepository(Rdv::class)
  1925.             ->findRdvMyAudio(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1926.         $myAudioRdv count($audioRdv);
  1927.         /****  RDV BY GENDER ****/
  1928.         $myRdvByGender 0;
  1929.         $audioRdvGender $this->getDoctrine()
  1930.             ->getRepository(Rdv::class)
  1931.             ->countMaleAndFemalePatient(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1932.         $myRdvByGender $audioRdvGender;
  1933.         /****  RDV BY AGE ****/
  1934.         $myRdvByAge 0;
  1935.         $audioRdvAge $this->getDoctrine()
  1936.             ->getRepository(Rdv::class)
  1937.             ->countClientsByAgeGroupsPatient(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1938.         $myRdvByAge $audioRdvAge;
  1939.         //  dd($myRdvByAge);
  1940.         /**** MY LEAD ****/
  1941.         $myLeadCentre 0;
  1942.         $rdvsCanceled $this->getDoctrine()
  1943.             ->getRepository(Rdv::class)
  1944.             ->findCanceledRdvCentreBetweenDateWithoutTest(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1945.         foreach ($rdvsCanceled as $rdvc) {
  1946.             if (!is_null($rdvc->getIdClient())) {
  1947.                 $rdvClient $this->getDoctrine()
  1948.                     ->getRepository(Rdv::class)
  1949.                     ->findRDVLeadByClient(new DateTime($request->query->get('debut')), $request->query->get('centre'), $rdvc->getIdClient()->getID());
  1950.                 if (count($rdvClient) == 0) {
  1951.                     $myLeadCentre $myLeadCentre 1;
  1952.                 }
  1953.             }
  1954.         }
  1955.         /**** MY LEAD ADVANCED****/
  1956.         $myLeadAdvancedCentre 0;
  1957.         $rdvsCanceledA $this->getDoctrine()
  1958.             ->getRepository(Rdv::class)
  1959.             ->findCanceledRdvCentreBetweenDateWithTest(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1960.         foreach ($rdvsCanceledA as $rdvc) {
  1961.             if (!is_null($rdvc->getIdClient())) {
  1962.                 $rdvClient $this->getDoctrine()
  1963.                     ->getRepository(Rdv::class)
  1964.                     ->findRDVLeadByClient(new DateTime($request->query->get('debut')), $request->query->get('centre'), $rdvc->getIdClient()->getID());
  1965.                 if (count($rdvClient) == 0) {
  1966.                     $myLeadAdvancedCentre $myLeadAdvancedCentre 1;
  1967.                 }
  1968.             }
  1969.         }
  1970.         return $this->json([
  1971.             "rdvs" => count($rdvs),
  1972.             "rdvsFromTest" => count($rdvsWithTest),
  1973.             "allRdvs" => count($allRdvs),
  1974.             "rdvsCanceled" => count($allRdvsCanceled),
  1975.             "rdvsClosed" => $rdvsClosed,
  1976.             "myRdvByGender" => $myRdvByGender,
  1977.             "myLead" => $myLead,
  1978.             "myRdvByAge" => $myRdvByAge,
  1979.             "myAudioRdv" => $myAudioRdv,
  1980.             "myLeadAdvanced" => $myLeadAdvanced,
  1981.             "myRDVCentre" => $myrdvCentre,
  1982.             "myRDVAdancedCentre" => $myRdvAdvancedCentre,
  1983.             "myLeadCentre" => $myLeadCentre,
  1984.             "myLeadAdvancedCentre" => $myLeadAdvancedCentre,
  1985.             "rdvsCanceledCentre" => count($allRdvsCanceledCentre),
  1986.             "myFirstRdv" => $myFirstRdv,
  1987.             "status" => 200,
  1988.         ]);
  1989.     }
  1990.     /**
  1991.      * @Route("/rdvs/old/clientTemp/{id}", name="getOldRdvsByClientTempId", methods={"GET","HEAD"})
  1992.      */
  1993.     public function getOldRdvsByClientTempId(Request $requestClientTemp $clientTempPublicFunction $publicFunction)
  1994.     {
  1995.         if (!$request->query->get('token')) {
  1996.             return new Response(json_encode([
  1997.                 "message" => "Pas de token n'a été spécifié",
  1998.                 "status" => 401,
  1999.             ]), 401);
  2000.         }
  2001.         $entityManager $this->getDoctrine()->getManager();
  2002.         /** @var Token */
  2003.         $token $this->getDoctrine()
  2004.             ->getRepository(Token::class)
  2005.             ->findOneBy(['token' => $request->query->get('token')]);
  2006.         if (!$token) {
  2007.             return new Response(json_encode([
  2008.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2009.                 "status" => 404,
  2010.             ]), 404);
  2011.         }
  2012.         // get token age
  2013.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2014.         // if the token if older than 7 days
  2015.         if ($dateDiff->7) {
  2016.             $entityManager->remove($token);
  2017.             $entityManager->flush();
  2018.             return $this->json([
  2019.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2020.                 'path' => 'src/Controller/ClientController.php',
  2021.                 "status" => 401,
  2022.             ], 401);
  2023.         }
  2024.         if ($clientTemp->getIdAudio() != $token->getIdAudio()) {
  2025.             return new Response(json_encode([
  2026.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  2027.                 "status" => 404,
  2028.             ]), 404);
  2029.         }
  2030.         if ($request->query->get('audio')) {
  2031.             /** @var ActivityRepository */
  2032.             $activityRepo $this->getDoctrine()->getRepository(Rdv::class);
  2033.             if ($request->query->get('limit')) {
  2034.                 /** @var Rdv[] */
  2035.                 $rdvs $activityRepo
  2036.                     ->findLastsOldRdvsWithLimitTemp($request->query->get('limit'), $clientTemp->getId(), $request->query->get('audio'), new DateTime());
  2037.                 $rdvResult = new ArrayCollection();
  2038.             } else {
  2039.                 /** @var Rdv[] */
  2040.                 $rdvs $activityRepo
  2041.                     ->findOldRdvsTemp($clientTemp->getId(), $request->query->get('audio'), new DateTime());
  2042.                 $rdvResult = new ArrayCollection();
  2043.             }
  2044.             foreach ($rdvs as $rdv) {
  2045.                 if ($rdv->getIdEtat()->getId() != 1) {
  2046.                     continue;
  2047.                 }
  2048.                 /** @var AudioMotif */
  2049.                 $audioMotif $this->getDoctrine()
  2050.                     ->getRepository(AudioMotif::class)
  2051.                     ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  2052.                 if (!$audioMotif) {
  2053.                     continue;
  2054.                 }
  2055.                 $duration '';
  2056.                 if (is_null($rdv->getDuration())) {
  2057.                     $duration $audioMotif->getDuration();
  2058.                 } else {
  2059.                     $duration $rdv->getDuration();
  2060.                 }
  2061.                 $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  2062.                 /** @var Rdv[] */
  2063.                 $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  2064.                     ->findAllReviewsCentre($rdvCentre->getId());
  2065.                 $rdvItem = [
  2066.                     "id" => $rdv->getId(),
  2067.                     "motif_id" => $rdv->getIdMotif()->getId(),
  2068.                     "duration" => $duration,
  2069.                     "color" => $audioMotif->getColor(),
  2070.                     "audio_id" => $rdv->getIdAudio()->getId(),
  2071.                     "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  2072.                     "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  2073.                     "client_id_temp" => $rdv->getIdClientTemp()->getId(),
  2074.                     "client_name" => $rdv->getIdClientTemp()->getName() . " " $rdv->getIdClientTemp()->getLastname(),
  2075.                     "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  2076.                     "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  2077.                     "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  2078.                     "testclient" => $rdv->getTestClient() ? [
  2079.                         "result" => $rdv->getTestClient()->getResultTonal(),
  2080.                         "date" => $rdv->getTestClient()->getDate(),
  2081.                         "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  2082.                     ] : null,
  2083.                     "name" => $rdvCentre->getName(),
  2084.                     "phone" => $rdvCentre->getPhone(),
  2085.                     "imgUrl" => $rdvCentre->getImgUrl(),
  2086.                     "address" => $rdvCentre->getAddress(),
  2087.                     "postale" => $rdvCentre->getPostale(),
  2088.                     "city" => $rdvCentre->getCity(),
  2089.                     "etat_id" => $rdvCentre->getId(),
  2090.                     "averageRating" => $publicFunction->calculateRating($centreRdvs),
  2091.                     "nbrReview" => count($centreRdvs),
  2092.                     "acceptedCurrency" => "CB Chèque",
  2093.                     "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  2094.                     "note" => $rdv->getNote(),
  2095.                     "comment" => $rdv->getComment(),
  2096.                     "review" => $rdv->getReview(),
  2097.                 ];
  2098.                 $rdvResult->add($rdvItem);
  2099.             }
  2100.         }
  2101.         if (count($rdvResult) > 0) {
  2102.             return new Response(json_encode(([
  2103.                 "rdv" => $rdvResult->toArray(),
  2104.                 "status" => 200,
  2105.             ])));
  2106.         } else {
  2107.             return new Response(json_encode(([
  2108.                 "message" => "Aucun rendez-vous n'a été trouvé!",
  2109.                 'path' => 'src/Controller/RdvController.php',
  2110.                 "status" => 404,
  2111.             ])));
  2112.         }
  2113.     }
  2114.     /**
  2115.      * @Route("/rdvs/old/clientTemp/{id}/centre", name="getOldRdvsByClientTempIdByCentre", methods={"GET","HEAD"})
  2116.      */
  2117.     public function getOldRdvsByClientTempIdByCentre(Request $requestClientTemp $clientTempPublicFunction $publicFunction)
  2118.     {
  2119.         if (!$request->query->get('token')) {
  2120.             return new Response(json_encode([
  2121.                 "message" => "Pas de token n'a été spécifié",
  2122.                 "status" => 401,
  2123.             ]), 401);
  2124.         }
  2125.         $entityManager $this->getDoctrine()->getManager();
  2126.         /** @var Token */
  2127.         $token $this->getDoctrine()
  2128.             ->getRepository(Token::class)
  2129.             ->findOneBy(['token' => $request->query->get('token')]);
  2130.         if (!$token) {
  2131.             return new Response(json_encode([
  2132.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2133.                 "status" => 404,
  2134.             ]), 404);
  2135.         }
  2136.         // get token age
  2137.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2138.         // if the token if older than 7 days
  2139.         if ($dateDiff->7) {
  2140.             $entityManager->remove($token);
  2141.             $entityManager->flush();
  2142.             return $this->json([
  2143.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2144.                 'path' => 'src/Controller/ClientController.php',
  2145.                 "status" => 401,
  2146.             ], 401);
  2147.         }
  2148.         $audioCentre $this->getDoctrine()
  2149.             ->getRepository(AudioCentre::class)
  2150.             ->findOneBy(['id_audio' => $token->getIdAudio()]);
  2151.         // we add the multi-centre so we wil desable the autorisation 
  2152.         /*
  2153.         if ($clientTemp->getIdCentre() != $audioCentre->getIdCentre()) {
  2154.             return new Response(json_encode([
  2155.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  2156.                 "status" => 404,
  2157.             ]), 404);
  2158.         }
  2159. */
  2160.         /** @var ActivityRepository */
  2161.         $activityRepo $this->getDoctrine()->getRepository(Rdv::class);
  2162.         if ($request->query->get('limit')) {
  2163.             /** @var Rdv[] */
  2164.             $rdvs $activityRepo
  2165.                 ->findLastsOldRdvsWithLimitTempByCentre($request->query->get('limit'), $clientTemp->getId(), $audioCentre->getIdCentre()->getId(), new DateTime());
  2166.             $rdvResult = new ArrayCollection();
  2167.         } else {
  2168.             /** @var Rdv[] */
  2169.             $rdvs $activityRepo
  2170.                 ->findOldRdvsTempByCentre($clientTemp->getId(), $audioCentre->getIdCentre()->getId(), new DateTime());
  2171.             $rdvResult = new ArrayCollection();
  2172.         }
  2173.         foreach ($rdvs as $rdv) {
  2174.             /*if ($rdv->getIdEtat()->getId() != 1) {
  2175.                 continue;
  2176.             }*/
  2177.             /** @var AudioMotif */
  2178.             $audioMotif $this->getDoctrine()
  2179.                 ->getRepository(AudioMotif::class)
  2180.                 ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  2181.             if (!$audioMotif) {
  2182.                 continue;
  2183.             }
  2184.             $duration '';
  2185.             if (is_null($rdv->getDuration())) {
  2186.                 $duration $audioMotif->getDuration();
  2187.             } else {
  2188.                 $duration $rdv->getDuration();
  2189.             }
  2190.             $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  2191.             /** @var Rdv[] */
  2192.             $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  2193.                 ->findAllReviewsCentre($rdvCentre->getId());
  2194.             $rdvItem = [
  2195.                 "id" => $rdv->getId(),
  2196.                 "motif_id" => $rdv->getIdMotif()->getId(),
  2197.                 "duration" => $duration,
  2198.                 "color" => $audioMotif->getColor(),
  2199.                 "audio_id" => $rdv->getIdAudio()->getId(),
  2200.                 "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  2201.                 "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  2202.                 "client_id_temp" => $rdv->getIdClientTemp()->getId(),
  2203.                 "client_name" => $rdv->getIdClientTemp()->getName() . " " $rdv->getIdClientTemp()->getLastname(),
  2204.                 "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  2205.                 "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  2206.                 "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  2207.                 "testclient" => $rdv->getTestClient() ? [
  2208.                     "result" => $rdv->getTestClient()->getResultTonal(),
  2209.                     "date" => $rdv->getTestClient()->getDate(),
  2210.                     "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  2211.                 ] : null,
  2212.                 "name" => $rdvCentre->getName(),
  2213.                 "phone" => $rdvCentre->getPhone(),
  2214.                 "imgUrl" => $rdvCentre->getImgUrl(),
  2215.                 "address" => $rdvCentre->getAddress(),
  2216.                 "postale" => $rdvCentre->getPostale(),
  2217.                 "city" => $rdvCentre->getCity(),
  2218.                 "etat_id" => $rdvCentre->getId(),
  2219.                 "averageRating" => $publicFunction->calculateRating($centreRdvs),
  2220.                 "nbrReview" => count($centreRdvs),
  2221.                 "acceptedCurrency" => "CB Chèque",
  2222.                 "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  2223.                 "note" => $rdv->getNote(),
  2224.                 "comment" => $rdv->getComment(),
  2225.                 "review" => $rdv->getReview(),
  2226.                 "status" => $rdv->getIdEtat()->getLibelle()
  2227.             ];
  2228.             $rdvResult->add($rdvItem);
  2229.         }
  2230.         if (count($rdvResult) > 0) {
  2231.             return new Response(json_encode(([
  2232.                 "rdv" => $rdvResult->toArray(),
  2233.                 "status" => 200,
  2234.             ])));
  2235.         } else {
  2236.             return new Response(json_encode(([
  2237.                 "message" => "Aucun rendez-vous n'a été trouvé!",
  2238.                 'path' => 'src/Controller/RdvController.php',
  2239.                 "status" => 404,
  2240.             ])));
  2241.         }
  2242.     }
  2243.     /**
  2244.      * @Route("/rdvs/clientTemp/{id}", name="getRdvsByClientTempID", methods={"GET","HEAD"})
  2245.      */
  2246.     public function getRdvsByClientTempID(Request $requestClientTemp $clientTempPublicFunction $publicFunction)
  2247.     {
  2248.         if (!$request->query->get('token')) {
  2249.             return new Response(json_encode([
  2250.                 "message" => "Pas de token n'a été spécifié",
  2251.                 "status" => 401,
  2252.             ]), 401);
  2253.         }
  2254.         $entityManager $this->getDoctrine()->getManager();
  2255.         /** @var Token */
  2256.         $token $this->getDoctrine()
  2257.             ->getRepository(Token::class)
  2258.             ->findOneBy(['token' => $request->query->get('token')]);
  2259.         if (!$token) {
  2260.             return new Response(json_encode([
  2261.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2262.                 "status" => 404,
  2263.             ]), 404);
  2264.         }
  2265.         // get token age
  2266.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2267.         // if the token if older than 7 days
  2268.         if ($dateDiff->7) {
  2269.             $entityManager->remove($token);
  2270.             $entityManager->flush();
  2271.             return $this->json([
  2272.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2273.                 'path' => 'src/Controller/ClientController.php',
  2274.                 "status" => 401,
  2275.             ], 401);
  2276.         }
  2277.         if ($clientTemp->getIdAudio() != $token->getIdAudio()) {
  2278.             return new Response(json_encode([
  2279.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  2280.                 "status" => 404,
  2281.             ]), 404);
  2282.         }
  2283.         /** @var Rdv[] */
  2284.         $rdvs $this->getDoctrine()
  2285.             ->getRepository(Rdv::class)
  2286.             ->findBy(['id_client_temp' => $clientTemp->getId(), 'id_audio' => $token->getIdAudio()]);
  2287.         $rdvResult = new ArrayCollection();
  2288.         if ($request->query->get('old')) {
  2289.             $oldRdvResult = new ArrayCollection();
  2290.         }
  2291.         foreach ($rdvs as $rdv) {
  2292.             if ($rdv->getIdEtat()->getId() != null) {
  2293.                 if ($rdv->getIdEtat()->getId() == 1) {
  2294.                     /** @var AudioMotif */
  2295.                     $audioMotif $this->getDoctrine()
  2296.                         ->getRepository(AudioMotif::class)
  2297.                         ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $token->getIdAudio()]);
  2298.                     /** @var Rdv[] */
  2299.                     $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  2300.                         ->findAllReviewsCentre($rdv->getIdCentre()->getId());
  2301.                     $duration '';
  2302.                     if (is_null($rdv->getDuration())) {
  2303.                         $duration $audioMotif->getDuration();
  2304.                     } else {
  2305.                         $duration $rdv->getDuration();
  2306.                     }
  2307.                     $rdvItem = [
  2308.                         "id" => $rdv->getId(),
  2309.                         "motif_id" => $rdv->getIdMotif()->getId(),
  2310.                         "duration" => $duration,
  2311.                         "color" => $audioMotif->getColor(),
  2312.                         "audio_id" => $rdv->getIdAudio()->getId(),
  2313.                         "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  2314.                         "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  2315.                         "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  2316.                         "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  2317.                         "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  2318.                         "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  2319.                         "client_name" => $rdv->getIdClientTemp()->getName() . " " $rdv->getIdClientTemp()->getLastname(),
  2320.                         "averageRating" => $publicFunction->calculateRating($centreRdvs),
  2321.                         "nbrReview" => count($centreRdvs),
  2322.                         "acceptedCurrency" => "CB Chèque",
  2323.                         "name" => $rdv->getIdCentre()->getName(),
  2324.                         "imgUrl" => $rdv->getIdCentre()->getImgUrl(),
  2325.                         "address" => $rdv->getIdCentre()->getAddress(),
  2326.                         "phone" => $rdv->getIdCentre()->getPhone(),
  2327.                         "etat_id" => $rdv->getIdEtat()->getId(),
  2328.                         "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  2329.                         "comment" => $rdv->getComment(),
  2330.                         "note" => $rdv->getNote(),
  2331.                         "review" => $rdv->getReview(),
  2332.                     ];
  2333.                     if ($rdv->getDate() >= new DateTime()) {
  2334.                         $rdvResult->add($rdvItem);
  2335.                     } else if ($request->query->get('old')) {
  2336.                         $oldRdvResult->add($rdvItem);
  2337.                     }
  2338.                 }
  2339.             }
  2340.         }
  2341.         if ($request->query->get('old')) {
  2342.             if (count($rdvResult) > || count($oldRdvResult) > 0) {
  2343.                 return new Response(json_encode(([
  2344.                     "rdv" => $rdvResult->toArray(),
  2345.                     "oldRdv" => $oldRdvResult->toArray(),
  2346.                     "status" => 200,
  2347.                 ])));
  2348.             } else {
  2349.                 return new Response(json_encode(([
  2350.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  2351.                     'path' => 'src/Controller/RdvController.php',
  2352.                     "status" => 404,
  2353.                 ])));
  2354.             }
  2355.         } else {
  2356.             if (count($rdvResult) > 0) {
  2357.                 return new Response(json_encode(([
  2358.                     "content" => $rdvResult->toArray(),
  2359.                     "status" => 200,
  2360.                 ])));
  2361.             } else {
  2362.                 return new Response(json_encode(([
  2363.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  2364.                     'path' => 'src/Controller/RdvController.php',
  2365.                     "status" => 404,
  2366.                 ])));
  2367.             }
  2368.         }
  2369.     }
  2370.     /**
  2371.      * @Route("/rdvs/clientTemp/{id}/centre", name="getRdvsByClientTempIDByCentre", methods={"GET","HEAD"})
  2372.      */
  2373.     public function getRdvsByClientTempIDByCentre(Request $requestClientTemp $clientTempPublicFunction $publicFunction)
  2374.     {
  2375.         if (!$request->query->get('token')) {
  2376.             return new Response(json_encode([
  2377.                 "message" => "Pas de token n'a été spécifié",
  2378.                 "status" => 401,
  2379.             ]), 401);
  2380.         }
  2381.         $entityManager $this->getDoctrine()->getManager();
  2382.         /** @var Token */
  2383.         $token $this->getDoctrine()
  2384.             ->getRepository(Token::class)
  2385.             ->findOneBy(['token' => $request->query->get('token')]);
  2386.         if (!$token) {
  2387.             return new Response(json_encode([
  2388.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2389.                 "status" => 404,
  2390.             ]), 404);
  2391.         }
  2392.         // get token age
  2393.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2394.         // if the token if older than 7 days
  2395.         if ($dateDiff->7) {
  2396.             $entityManager->remove($token);
  2397.             $entityManager->flush();
  2398.             return $this->json([
  2399.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2400.                 'path' => 'src/Controller/ClientController.php',
  2401.                 "status" => 401,
  2402.             ], 401);
  2403.         }
  2404.         $audioCentre $this->getDoctrine()
  2405.             ->getRepository(AudioCentre::class)
  2406.             ->findOneBy(['id_audio' => $token->getIdAudio()]);
  2407.         // we add the multi-centre so we wil desable the autorisation 
  2408.         /*    
  2409.         if ($clientTemp->getIdCentre() != $audioCentre->getIdCentre()) {
  2410.             return new Response(json_encode([
  2411.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  2412.                 "status" => 404,
  2413.             ]), 404);
  2414.         }*/
  2415.         /** @var Rdv[] */
  2416.         $rdvs $this->getDoctrine()
  2417.             ->getRepository(Rdv::class)
  2418.             ->findBy(['id_client_temp' => $clientTemp->getId(), 'id_centre' => $audioCentre->getIdCentre()]);
  2419.         $rdvResult = new ArrayCollection();
  2420.         if ($request->query->get('old')) {
  2421.             $oldRdvResult = new ArrayCollection();
  2422.         }
  2423.         foreach ($rdvs as $rdv) {
  2424.             if ($rdv->getIdEtat()->getId() != null) {
  2425.                 if ($rdv->getIdEtat()->getId() != 6) {
  2426.                     // if ($rdv->getIdEtat()->getId() == 1) {
  2427.                     /** @var AudioMotif */
  2428.                     $audioMotif $this->getDoctrine()
  2429.                         ->getRepository(AudioMotif::class)
  2430.                         ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  2431.                     /** @var Rdv[] */
  2432.                     $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  2433.                         ->findAllReviewsCentre($rdv->getIdCentre()->getId());
  2434.                     $duration '';
  2435.                     if (is_null($rdv->getDuration())) {
  2436.                         $duration $audioMotif->getDuration();
  2437.                     } else {
  2438.                         $duration $rdv->getDuration();
  2439.                     }
  2440.                     $rdvItem = [
  2441.                         "id" => $rdv->getId(),
  2442.                         "motif_id" => $rdv->getIdMotif()->getId(),
  2443.                         "duration" => $duration,
  2444.                         "color" => $audioMotif->getColor(),
  2445.                         "audio_id" => $rdv->getIdAudio()->getId(),
  2446.                         "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  2447.                         "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  2448.                         "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  2449.                         "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  2450.                         "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  2451.                         "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  2452.                         "client_name" => $rdv->getIdClientTemp()->getName() . " " $rdv->getIdClientTemp()->getLastname(),
  2453.                         "averageRating" => $publicFunction->calculateRating($centreRdvs),
  2454.                         "nbrReview" => count($centreRdvs),
  2455.                         "acceptedCurrency" => "CB Chèque",
  2456.                         "name" => $rdv->getIdCentre()->getName(),
  2457.                         "imgUrl" => $rdv->getIdCentre()->getImgUrl(),
  2458.                         "address" => $rdv->getIdCentre()->getAddress(),
  2459.                         "phone" => $rdv->getIdCentre()->getPhone(),
  2460.                         "etat_id" => $rdv->getIdEtat()->getId(),
  2461.                         "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  2462.                         "comment" => $rdv->getComment(),
  2463.                         "note" => $rdv->getNote(),
  2464.                         "review" => $rdv->getReview(),
  2465.                         "status" => $rdv->getIdEtat()->getLibelle()
  2466.                     ];
  2467.                     if ($rdv->getDate() >= new DateTime()) {
  2468.                         $rdvResult->add($rdvItem);
  2469.                     } else if ($request->query->get('old')) {
  2470.                         $oldRdvResult->add($rdvItem);
  2471.                     }
  2472.                 }
  2473.             }
  2474.         }
  2475.         if ($request->query->get('old')) {
  2476.             if (count($rdvResult) > || count($oldRdvResult) > 0) {
  2477.                 return new Response(json_encode(([
  2478.                     "rdv" => $rdvResult->toArray(),
  2479.                     "oldRdv" => $oldRdvResult->toArray(),
  2480.                     "status" => 200,
  2481.                 ])));
  2482.             } else {
  2483.                 return new Response(json_encode(([
  2484.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  2485.                     'path' => 'src/Controller/RdvController.php',
  2486.                     "status" => 404,
  2487.                 ])));
  2488.             }
  2489.         } else {
  2490.             if (count($rdvResult) > 0) {
  2491.                 return new Response(json_encode(([
  2492.                     "content" => $rdvResult->toArray(),
  2493.                     "status" => 200,
  2494.                 ])));
  2495.             } else {
  2496.                 return new Response(json_encode(([
  2497.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  2498.                     'path' => 'src/Controller/RdvController.php',
  2499.                     "status" => 404,
  2500.                 ])));
  2501.             }
  2502.         }
  2503.     }
  2504.     /**
  2505.      * @Route("/rdv", name="postRdv", methods={"POST"})
  2506.      */
  2507.     public function postRdv(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendarRdvSmsService $rdvSmsAppointmentCallService $Callservice): Response
  2508.     {
  2509.         $data json_decode($request->getContent(), true);
  2510.         if (!isset($data["token"])) {
  2511.             return new Response(json_encode([
  2512.                 "message" => "Pas de token n'a été spécifié",
  2513.                 "status" => 401,
  2514.             ]), 401);
  2515.         }
  2516.         $entityManager $this->getDoctrine()->getManager();
  2517.         /** @var Token */
  2518.         $token $this->getDoctrine()
  2519.             ->getRepository(Token::class)
  2520.             ->findOneBy(['token' => $data["token"]]);
  2521.         if (!$token) {
  2522.             return new Response(json_encode([
  2523.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2524.                 "status" => 404,
  2525.             ]), 404);
  2526.         }
  2527.         // get token age
  2528.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2529.         // if the token if older than 7 days
  2530.         if ($dateDiff->7) {
  2531.             $entityManager->remove($token);
  2532.             $entityManager->flush();
  2533.             return $this->json([
  2534.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2535.                 'path' => 'src/Controller/ClientController.php',
  2536.                 "status" => 401,
  2537.             ], 401);
  2538.         }
  2539.         // makes the rdv
  2540.         $rdv = new Rdv();
  2541.         if ($token->getIdAudio()) {
  2542.             //if the token if for an audio
  2543.             $audio $token->getIdAudio();
  2544.             if ((isset($data["client_id"]))) {
  2545.                 $client $this->getDoctrine()
  2546.                     ->getRepository(Client::class)
  2547.                     ->findOneBy(['id' => $data["client_id"]]);
  2548.             } else {
  2549.                 $client $this->getDoctrine()
  2550.                     ->getRepository(ClientTemp::class)
  2551.                     ->findOneBy(['id' => $data["client_id_temp"]]);
  2552.             }
  2553.             if ($client == null) {
  2554.                 return new Response(json_encode(([
  2555.                     'message' => 'Error, no client found at this id',
  2556.                     'path' => 'src/Controller/RdvController.php',
  2557.                     "status" => 400,
  2558.                 ])), 400);
  2559.             }
  2560.         } elseif ($token->getIdClient()) {
  2561.             //if the token if for a client
  2562.             $client $token->getIdClient();
  2563.             /** @var ActivityRepository */
  2564.             $activityRepo $this->getDoctrine();
  2565.             /** @var TestClient */
  2566.             $testClient $activityRepo
  2567.                 ->getRepository(TestClient::class)
  2568.                 ->getLatestTestClient($client);
  2569.             // add the test to the rdv if the client had one
  2570.             if ($testClient)
  2571.             // add the test to the rdv if the test isn't already on another rdv
  2572.             {
  2573.                 if (!$testClient->getRdv()) {
  2574.                     $rdv->setTestClient($testClient);
  2575.                 }
  2576.             }
  2577.             /** @var Audio */
  2578.             $audio $this->getDoctrine()
  2579.                 ->getRepository(Audio::class)
  2580.                 ->findOneBy(['id' => $data["audio_id"]]);
  2581.             if (isset($data["proche_id"])) {
  2582.                 $proche $this->getDoctrine()
  2583.                     ->getRepository(Proches::class)
  2584.                     ->findOneBy(['id' => $data["proche_id"], "id_client" => $client]);
  2585.             }
  2586.             if (!$audio) {
  2587.                 return new Response(json_encode(([
  2588.                     'message' => "Erreur, pas d'audio n'a été trouvé à cette id.",
  2589.                     'path' => 'src/Controller/RdvController.php',
  2590.                 ])), 400);
  2591.             }
  2592.             /** @var ClientBlocked */
  2593.             $clientBlocked $this->getDoctrine()
  2594.                 ->getRepository(ClientBlocked::class)
  2595.                 ->findOneBy(["id_audio" => $audio"id_client" => $client]);
  2596.             if ($clientBlocked) {
  2597.                 return new Response(json_encode(([
  2598.                     'message' => 'Erreur, vous avez été bloqué par cette audioprothésiste.',
  2599.                     'path' => 'src/Controller/RdvController.php',
  2600.                 ])), 400);
  2601.             }
  2602.             // set the rdv test
  2603.         } else {
  2604.             return new Response(json_encode(([
  2605.                 'message' => "Erreur, ce token n'est pas celui d'un client ou audioprothèsiste.",
  2606.                 'path' => 'src/Controller/RdvController.php',
  2607.             ])), 400);
  2608.         }
  2609.         $rdv->setIdAudio($audio);
  2610.         if (isset($proche)) {
  2611.             $rdv->setIdProche($proche);
  2612.         }
  2613.         if (isset($data["client_id_temp"])) {
  2614.             $rdv->setIdClientTemp($client);
  2615.         } else {
  2616.             $rdv->setIdClient($client);
  2617.         }
  2618.         if (isset($data["isMyaudio"])) {
  2619.             $rdv->setIsMyaudio(true);
  2620.         }
  2621.         if (isset($data["isRdvLead"])) {
  2622.             $rdv->setIsRdvLp(true);
  2623.         }
  2624.         if (isset($data["isRdvRapide"])) {
  2625.             $rdv->setIsRdvRapide(true);
  2626.         }
  2627.         if (isset($data["duree"])) {
  2628.             $rdv->setDuration($data["duree"]);
  2629.         }
  2630.         if (isset($data["color"])) {
  2631.             $rdv->setColor($data["color"]);
  2632.         }
  2633.         if (isset($data["lead"])) {
  2634.             $lead $this->getDoctrine()
  2635.                 ->getRepository(LeadRdv::class)
  2636.                 ->find($data["lead"]);
  2637.             $lead->setRdv($rdv);
  2638.             $leadStatus $this->entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'rdv_valider']);
  2639.             if ($leadStatus) {
  2640.                 $lead->setLeadStatus($leadStatus);
  2641.             }
  2642.         }
  2643.         /** @var Centre */
  2644.         if (isset($data["centre_id"])) {
  2645.             $centre $this->getDoctrine()
  2646.                 ->getRepository(Centre::class)
  2647.                 ->findOneBy(['id' => $data["centre_id"]]);
  2648.             if ($centre == null) {
  2649.                 return new Response(json_encode(([
  2650.                     'message' => 'Error, no centre found at this id',
  2651.                     'path' => 'src/Controller/RdvController.php',
  2652.                     "status" => 400,
  2653.                 ])), 400);
  2654.             }
  2655.             /** @var AudioCentre */
  2656.             $liaison $this->getDoctrine()
  2657.                 ->getRepository(AudioCentre::class)
  2658.                 ->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
  2659.             if ($liaison == null) {
  2660.                 return new Response(json_encode(([
  2661.                     'message' => 'Error, audio isnt part of the centre',
  2662.                     'path' => 'src/Controller/RdvController.php',
  2663.                     "status" => 400,
  2664.                 ])), 400);
  2665.             }
  2666.             $rdv->setIdCentre($centre);
  2667.         } elseif (isset($data["lieu_id"]) && $audio->getIsIndie()) {
  2668.             // tries to set the lieu if it's an audio indie
  2669.             $lieu $this->getDoctrine()
  2670.                 ->getRepository(Lieu::class)
  2671.                 ->findOneBy(['id' => $data["lieu_id"], 'id_gerant' => $data["audio_id"]]);
  2672.             if ($lieu == null) {
  2673.                 return new Response(json_encode(([
  2674.                     'message' => 'Error, no lieu found at this id',
  2675.                     'path' => 'src/Controller/RdvController.php',
  2676.                     "status" => 400,
  2677.                 ])), 400);
  2678.             }
  2679.             $rdv->setIdLieu($lieu);
  2680.         } else {
  2681.             return new Response(json_encode(([
  2682.                 'message' => 'Error, no lieu/centre id',
  2683.                 'path' => 'src/Controller/RdvController.php',
  2684.                 "status" => 400,
  2685.             ])), 400);
  2686.         }
  2687.         /** @var Motif */
  2688.         $motif $this->getDoctrine()
  2689.             ->getRepository(Motif::class)
  2690.             ->find($data["motif_id"]);
  2691.         if ($motif == null) {
  2692.             return new Response(json_encode(([
  2693.                 'message' => 'Error, no motif found at this id',
  2694.                 'path' => 'src/Controller/RdvController.php',
  2695.                 "status" => 400,
  2696.             ])), 400);
  2697.         }
  2698.         /** @var AudioMotif */
  2699.         $audioMotif $this->getDoctrine()
  2700.             ->getRepository(AudioMotif::class)
  2701.             ->findOneBy(["id_audio" => $audio->getId(), "id_motif" => $data["motif_id"]]);
  2702.         if ($audioMotif == null) {
  2703.             return new Response(json_encode(([
  2704.                 'message' => 'Error, no motif of this id found at this audio',
  2705.                 'path' => 'src/Controller/RdvController.php',
  2706.                 "status" => 400,
  2707.             ])), 400);
  2708.         }
  2709.         // remove the taken schedule by rdv to make sure there is no overlap
  2710.         $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  2711.         if (isset($data["note"])) {
  2712.             $rdv->setNote($data["note"]);
  2713.         }
  2714.         // test if the audio is available
  2715.         if ($audio->getIsIndie()) {
  2716.             if (isset($data["centre_id"])) {
  2717.                 if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  2718.                     return new Response(json_encode(([
  2719.                         'message' => 'Error, no horaire found for this audio',
  2720.                         'path' => 'src/Controller/RdvController.php',
  2721.                         "status" => 400,
  2722.                     ])), 400);
  2723.                 }
  2724.                 if ($publicFunction->calculScheduleFitDate($audio\DateTime::createFromFormat("d/m/Y H:i"$data["date"]), $audioMotif->getDuration(), $centre) == false) {
  2725.                     return new Response(json_encode(([
  2726.                         'message' => 'Error, no timestamp found at this time. Line n°' __LINE__,
  2727.                         'path' => 'src/Controller/RdvController.php',
  2728.                         "status" => 400,
  2729.                     ])), 400);
  2730.                 }
  2731.                 $remplacant_id $publicFunction->checkIfRemplacant($liaison->getHoraire(), $date);
  2732.             } else {
  2733.                 if ($lieu->getHoraire() == null || $lieu->getHoraire() == []) {
  2734.                     return new Response(json_encode(([
  2735.                         'message' => 'Error, no horaire found for this audio',
  2736.                         'path' => 'src/Controller/RdvController.php',
  2737.                         "status" => 400,
  2738.                     ])), 400);
  2739.                 }
  2740.                 if ($publicFunction->calculScheduleFitDate($audio\DateTime::createFromFormat("d/m/Y H:i"$data["date"]), $audioMotif->getDuration(), null$lieu) == false) {
  2741.                     return new Response(json_encode(([
  2742.                         'message' => 'Error, no timestamp found at this time. Line n°' __LINE__,
  2743.                         'path' => 'src/Controller/RdvController.php',
  2744.                         "status" => 400,
  2745.                     ])), 400);
  2746.                 }
  2747.                 $remplacant_id $publicFunction->checkIfRemplacant($lieu->getHoraire(), $date);
  2748.             }
  2749.         } else {
  2750.             if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  2751.                 return new Response(json_encode(([
  2752.                     'message' => 'Error, no horaire found for this audio',
  2753.                     'path' => 'src/Controller/RdvController.php',
  2754.                     "status" => 400,
  2755.                 ])), 400);
  2756.             }
  2757.             /*  if (!$publicFunction->calculScheduleFitDate($audio, \DateTime::createFromFormat("d/m/Y H:i", $data["date"]), $audioMotif->getDuration(), $centre))
  2758.                 return new Response(json_encode(([
  2759.                     'message' => "Error, no timestamp found at this time. Motif size: {$audioMotif->getDuration()} Line n°" . __LINE__,
  2760.                     'path' => 'src/Controller/RdvController.php',
  2761.                     "status" => 400,
  2762.                 ])), 400);*/
  2763.             $remplacant_id $publicFunction->checkIfRemplacant($liaison->getHoraire(), \DateTime::createFromFormat("d/m/Y H:i"$data["date"]));
  2764.         }
  2765.         $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  2766.         $existingRdv $this->getDoctrine()
  2767.             ->getRepository(Rdv::class)
  2768.             ->findOneBy([
  2769.                 'date' => $date,
  2770.                 'id_audio' => $audio,
  2771.                 'id_centre' => $rdv->getIdCentre() ?? null,
  2772.                 'id_lieu' => $rdv->getIdLieu()   ?? null,
  2773.             ]);
  2774.         if ($existingRdv) {
  2775.             return new Response(json_encode([
  2776.                 'message' => 'Un rendez-vous est déjà pris pour cette date et ce créneau.',
  2777.                 'status' => 400,
  2778.             ]), 400);
  2779.         }
  2780.         $rdv->setDate($date);
  2781.         $rdv->setDateCreation(\DateTime::createFromFormat("d/m/Y H:i"date('d/m/Y H:i')));
  2782.         /** @var EtatRdv */
  2783.         $etat $this->getDoctrine()
  2784.             ->getRepository(EtatRdv::class)
  2785.             ->findOneBy(['id' => $data["etat_id"]]);
  2786.         if ($etat == null) {
  2787.             return new Response(json_encode(([
  2788.                 'message' => 'Error, no etat found at this id',
  2789.                 'path' => 'src/Controller/RdvController.php',
  2790.                 "status" => 400,
  2791.             ])), 400);
  2792.         }
  2793.         $rdv->setIdEtat($etat);
  2794.         $rdv->setIdMotif($motif);
  2795.         $rdv->setIsAbsence(0);
  2796.         $rdv->setCacher(0);
  2797.         if ($remplacant_id != -1) {
  2798.             $remplacant $this->getDoctrine()
  2799.                 ->getRepository(Remplacant::class)
  2800.                 ->find($remplacant_id);
  2801.             $rdv->setRemplacant($remplacant);
  2802.         }
  2803.         $entityManager $this->getDoctrine()->getManager();
  2804.         $entityManager->persist($rdv);
  2805.         $entityManager->flush();
  2806.         /// SMSEMAIL A décommenter pour autoriser l'envoi de sms / email à la création de rdv par l'audio / le client SMSEMAIL ///
  2807.         $date $rdv->getDate();
  2808.         $smsDate $date->format('d-m-Y H:i');
  2809.         $locale 'fr_FR';
  2810.         $formatter = new IntlDateFormatter(
  2811.             $locale,
  2812.             IntlDateFormatter::FULL,
  2813.             IntlDateFormatter::SHORT,
  2814.             null,
  2815.             IntlDateFormatter::GREGORIAN,
  2816.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  2817.         );
  2818.         $smsDateLongFormat $formatter->format($date);
  2819.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  2820.         $client->setIdCentre($rdv->getIdCentre());
  2821.         $client->setIdAudio($rdv->getIdAudio());
  2822.         $entityManager->persist($client);
  2823.         $entityManager->flush();
  2824.         // client notif mail Sms
  2825.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  2826.         $frenchDate ucfirst($frenchDate);
  2827.         $responses = [
  2828.             'rangeAge' => isset($data['rangeAge']) ? $data['rangeAge'] : null,
  2829.             'situations' => (isset($data['situations']) && !empty($data['situations'])) ? implode(", "$data['situations']) : null,
  2830.             'equipeAppareil' => isset($data['equipe']) ? $data['equipe'] : null,
  2831.             'durationEquipe' => isset($data['durationEquipe']) ? $data['durationEquipe'] : null,
  2832.             'bilanAuditif' => isset($data['bilanAuditif']) ? $data['bilanAuditif'] : null,
  2833.             'ordonance' => isset($data['ordonnance']) ? $data['ordonnance'] : null,
  2834.             'dateOrdonance' => isset($data['dateOrdonance']) ? $data['dateOrdonance'] : null,
  2835.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  2836.         ];
  2837.         $paramsSourceLead = [
  2838.             'trafficSource' => isset($data['traffic_source']) ? $data['traffic_source'] : null,
  2839.             'articleName' => isset($data['article_name']) ? $data['article_name'] : null,
  2840.             'lpVersion' => isset($data['lp_version']) ? $data['lp_version'] : null,
  2841.         ];
  2842.         $params = array(
  2843.             "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  2844.             "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  2845.             "date" => $smsDateLongFormat,
  2846.             "RdvDate" => $smsDateLongFormat,
  2847.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  2848.             "centerName" => $rdv->getIdCentre()->getName(),
  2849.             "prenom" => $client->getName(),
  2850.             "centerAddress" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  2851.             "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  2852.             'motif' => $rdv->getIdMotif()->getTitre(),
  2853.             "centerCity" => $rdv->getIdCentre()->getCity(),
  2854.             "audioName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  2855.             'titre' => "Votre rendez-vous est validé le " substr($smsDate010) . " à "  substr($smsDate1115),
  2856.             "position" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  2857.             "address" => $rdv->getIdCentre()->getAddress(),
  2858.             "postal" => $rdv->getIdCentre()->getPostale(),
  2859.             "city" => $rdv->getIdCentre()->getCity(),
  2860.             "clientEmail" => $client->getMail(),
  2861.             "clientPassword" => isset($data["passwordGenerated"]) ? $data["passwordGenerated"] : null,
  2862.             "clientAddress" => $client->getAddress(),
  2863.             "clientPostal" => $client->getPostal(),
  2864.             "clientCity" => $client->getCity(),
  2865.             "audioName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  2866.             "frenchDate" => $frenchDate,
  2867.             "heure" => substr($smsDate1115),
  2868.             "centerName" => $rdv->getIdCentre()->getName(),
  2869.             "audioMail" => $rdv->getIdAudio()->getMail(),
  2870.             "modifUrl" => "{$_ENV['BASE_client']}mes-rendez-vous",
  2871.         );
  2872.         $paramsPatient $params;
  2873.         $isNew false;
  2874.         if (isset($data["isLead"]) && isset($data["passwordGenerated"]) != null) {
  2875.             $subject "✅Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  2876.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject189);
  2877.             $isNew true;
  2878.         } else {
  2879.             $subject "Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  2880.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject181);
  2881.         }
  2882.         $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.";
  2883.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  2884.         // audio Notif mail SMS
  2885.         $birthday $rdv->getIdClient()->getBirthdate();
  2886.         $params = array(
  2887.             "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  2888.             "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  2889.             "date" => substr($smsDate010),
  2890.             "heure" => substr($smsDate1115),
  2891.             "mail" => $client->getMail(),
  2892.             "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  2893.             'telClient' => $client->getPhone(),
  2894.             'phone' => $client->getPhone(),
  2895.             'clientCivilite' => $client->getCivilite(),
  2896.             'clientNom' => $client->getLastname(),
  2897.             'clientPrenom' => $client->getName(),
  2898.             'clientPostal' => $client->getPostal(),
  2899.             'clientMail' => $client->getMail(),
  2900.             'clientPhone' => $client->getPhone(),
  2901.             'motif' => $rdv->getIdMotif()->getTitre(),
  2902.             'birthdate' => $client->getBirthdate() ? $client->getBirthdate()->format("d/m/Y") : null,
  2903.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  2904.             'centerName' => $rdv->getIdCentre()->getName(),
  2905.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  2906.             'centerCity' => $rdv->getIdCentre()->getCity(),
  2907.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  2908.             'idPatient' => $client->getId(),
  2909.             'proUrl' => "{$_ENV['BASE_logiciel']}",
  2910.             'frenchDate' => $frenchDate,
  2911.             'responses' => $responses,
  2912.         );
  2913.         $templateEmail 182;
  2914.         if (!empty($data['canMove'])) {
  2915.             $templateEmail 197;
  2916.         }
  2917.         $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  2918.         $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  2919.         if ($rdv->getIdAudio()->getConfirmRdvMail()) {
  2920.             $subject "✅Nouveau Rendez-vous My Audio le " $frenchDate " à " substr($smsDate1115);
  2921.             $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject$templateEmail);
  2922.         }
  2923.         if ($rdv->getIdAudio()->getConfirmRdvSms()) {
  2924.             $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.";
  2925.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  2926.         }
  2927.         // send notif to admin
  2928.         $paramsAdmin = array(
  2929.             "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  2930.             "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  2931.             "RdvDate" => substr($smsDate010),
  2932.             "heure" => substr($smsDate1115),
  2933.             "clientMail" => $client->getMail(),
  2934.             "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  2935.             'telClient' => $client->getPhone(),
  2936.             'clientNom' => $client->getLastname(),
  2937.             'clientPrenom' => $client->getName(),
  2938.             'clientCivilite' => $client->getCivilite(),
  2939.             'clientPostal' => $client->getPostal(),
  2940.             'clientPhone' => $client->getPhone(),
  2941.             'motif' => $rdv->getIdMotif()->getTitre(),
  2942.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  2943.             'centerName' => $rdv->getIdCentre()->getName(),
  2944.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  2945.             'centerCity' => $rdv->getIdCentre()->getCity(),
  2946.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  2947.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  2948.             'date' => substr($smsDate010),
  2949.             'urlApi' => "{$_ENV['BASE_API']}",
  2950.             'clientId' => $client->getId(),
  2951.             'centerId' => $rdv->getIdCentre()->getId(),
  2952.             'frenchDate' => $frenchDate,
  2953.             'responses' => $responses,
  2954.             'paramsSourceLead' => $paramsSourceLead
  2955.         );
  2956.         $subject "Nouveau RDV MA | RR - " $rdv->getIdCentre()->getName();
  2957.         $templateEmail 183;
  2958.         if (!empty($data['canMove'])) {
  2959.             $templateEmail 190;
  2960.         }
  2961.         if (!isset($data["isLead"])) {
  2962.             $publicFunction->sendEmail($paramsAdmin"lead.myaudio@gmail.com""my audio"$subject$templateEmail);
  2963.         }
  2964.         //$publicFunction->sendEmail($paramsAdmin,"testpation1254@yopmail.com","my audio", 'Nouveau RDV à My Audio Pro', $templateEmail);
  2965.         $publicFunction->sendEmail($paramsAdmin"contact@myaudio.fr""my audio"$subject$templateEmail);
  2966.         $publicFunction->sendEmail($paramsAdmin"lead.myaudio@gmail.com""my audio"$subject$templateEmail);
  2967.         // google calendar post
  2968.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  2969.             ->findBy(array('audio' => $audio->getId()));
  2970.         $data['rdv'] = $rdv->getId();
  2971.         if (isset($data['clientRdvLp']) && !empty($data['clientRdvLp'])) {
  2972.             $rdvLead $this->entityManager->getRepository(LeadRdv::class)->find($data['clientRdvLp']);
  2973.             if ($rdvLead) {
  2974.                 $leadStatus $this->entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'rdv_valider']);
  2975.                 if ($leadStatus) {
  2976.                     $rdvLead->setLeadStatus($leadStatus);
  2977.                     $rdvLead->setRdv($rdv);
  2978.                     $this->entityManager->flush();
  2979.                 }
  2980.             }
  2981.         }
  2982.         foreach ($synchronisations as $synchronisation) {
  2983.             if (!$synchronisation->getIsDeleted()) {
  2984.                 $googleCalendar->checkAndRefreshAccessToken($synchronisation);
  2985.                 $googleCalendar->createEvent($synchronisation$data);
  2986.             }
  2987.         }
  2988.         if (isset($data["isMyaudio"]) || isset($data["isRdvLead"]) || isset($data["isRdvRapide"])) {
  2989.             try {
  2990.                 $Callservice->handleCallCenterAfterRdv(
  2991.                     $rdv
  2992.                 );
  2993.                 $rdv->setIsNotificationRdvCallSent(1);
  2994.                 $this->entityManager->flush();
  2995.             } catch (\Exception $e) {
  2996.                 $this->logger->error("Erreur lors de l'appel de notification pour le RDV #{$rdv->getId()}: " $e->getMessage());
  2997.             }
  2998.         }
  2999.         return new Response(json_encode(([
  3000.             "id" => $rdv->getId(),
  3001.             "motif_id" => $rdv->getIdMotif()->getId(),
  3002.             "audio_id" => $rdv->getIdAudio()->getId(),
  3003.             "remplacant_id" => $remplacant_id == -null $remplacant_id,
  3004.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  3005.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  3006.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  3007.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  3008.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  3009.             "testclient" => $rdv->getTestClient() ? [
  3010.                 "result" => $rdv->getTestClient()->getResultTonal(),
  3011.                 "date" => $rdv->getTestClient()->getDate(),
  3012.                 "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  3013.             ] : null,
  3014.             "duration" => $audioMotif->getDuration(),
  3015.             "consigne" => $audioMotif->getConsigne(),
  3016.             "etat_id" => $rdv->getIdEtat()->getId(),
  3017.             "date" => $rdv->getDate(),
  3018.             "comment" => $rdv->getComment(),
  3019.             "centerName" => $rdv->getIdCentre()->getName(),
  3020.             "review" => $rdv->getReview(),
  3021.             "note" => $rdv->getNote(),
  3022.             "status" => 200,
  3023.             "paramsPatient" => $paramsPatient,
  3024.             "isNew" => $isNew,
  3025.         ])));
  3026.     }
  3027.     /**
  3028.      * @Route("/rdv/{id}/trusteduser", name="contactTrustedUser", methods={"POST"})
  3029.      */
  3030.     public function contactTrustedUser(Request $requestPublicFunction $publicFunction)
  3031.     {
  3032.         $pastDate $rdv->getDate();
  3033.         $data json_decode($request->getContent(), true);
  3034.         $entityManager $this->getDoctrine()->getManager();
  3035.         if (!isset($data["token"])) {
  3036.             return new Response(json_encode([
  3037.                 "message" => "Pas de token n'a été spécifié",
  3038.                 "status" => 401,
  3039.             ]), 401);
  3040.         }
  3041.         /** @var Token */
  3042.         $token $this->getDoctrine()
  3043.             ->getRepository(Token::class)
  3044.             ->findOneBy(['token' => $data["token"]]);
  3045.         if (!$token) {
  3046.             return new Response(json_encode([
  3047.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  3048.                 "status" => 404,
  3049.             ]), 404);
  3050.         }
  3051.         // get token age
  3052.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  3053.         // if the token if older than 7 days
  3054.         if ($dateDiff->7) {
  3055.             $entityManager->remove($token);
  3056.             $entityManager->flush();
  3057.             return $this->json([
  3058.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  3059.                 'path' => 'src/Controller/ClientController.php',
  3060.                 "status" => 401,
  3061.             ], 401);
  3062.         }
  3063.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  3064.             return new Response(json_encode([
  3065.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  3066.                 "status" => 404,
  3067.             ]), 404);
  3068.         }
  3069.         if (isset($data["date"])) {
  3070.             // remove the taken schedule by rdv to make sure there is no overlap
  3071.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  3072.             $audioMotif $this->getDoctrine()
  3073.                 ->getRepository(AudioMotif::class)
  3074.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  3075.             if ($audioMotif == null) {
  3076.                 return new Response(json_encode(([
  3077.                     'message' => 'Error, no motif of this id found at this audio',
  3078.                     'path' => 'src/Controller/RdvController.php',
  3079.                     "status" => 400,
  3080.                 ])), 400);
  3081.             }
  3082.             if ($rdv->getIdAudio()->getIsIndie()) {
  3083.                 if ($rdv->getIdCentre()) {
  3084.                     // regular centre audio indie
  3085.                     /** @var AudioCentre */
  3086.                     $liaison $this->getDoctrine()
  3087.                         ->getRepository(AudioCentre::class)
  3088.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  3089.                     if ($liaison == null) {
  3090.                         return new Response(json_encode(([
  3091.                             'message' => 'Error, audio isnt part of the centre',
  3092.                             'path' => 'src/Controller/RdvController.php',
  3093.                             "status" => 400,
  3094.                         ])), 400);
  3095.                     }
  3096.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  3097.                         return new Response(json_encode(([
  3098.                             'message' => 'Error, no horaire found for this audio',
  3099.                             'path' => 'src/Controller/RdvController.php',
  3100.                             "status" => 400,
  3101.                         ])), 400);
  3102.                     }
  3103.                     // if ($publicFunction->calculScheduleFitDate($liaison->getHoraire(), $rdv->getIdAudio(), $date, $audioMotif->getDuration(), $rdv->getIdCentre()) == false) {
  3104.                     //     return new Response(json_encode(([
  3105.                     //         'message' => 'Error, no timestamp found at this time',
  3106.                     //         'path' => 'src/Controller/RdvController.php',
  3107.                     //         "status" => 400,
  3108.                     //     ])),400);
  3109.                     // }
  3110.                 } else {
  3111.                     // lieu audio indie
  3112.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  3113.                         return new Response(json_encode(([
  3114.                             'message' => 'Error, no horaire found for this audio',
  3115.                             'path' => 'src/Controller/RdvController.php',
  3116.                             "status" => 400,
  3117.                         ])), 400);
  3118.                     }
  3119.                     // if ($publicFunction->calculScheduleFitDate($rdv->getIdLieu()->getHoraire(), $rdv->getIdAudio(), $date, $audioMotif->getDuration(), null, $rdv->getIdLieu()) == false) {
  3120.                     //     return new Response(json_encode(([
  3121.                     //         'message' => 'Error, no timestamp found at this time',
  3122.                     //         'path' => 'src/Controller/RdvController.php',
  3123.                     //         "status" => 400,
  3124.                     //     ])),400);
  3125.                     // }
  3126.                 }
  3127.             } else {
  3128.                 // regular centre
  3129.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  3130.                     return new Response(json_encode(([
  3131.                         'message' => 'Error, no horaire found for this audio',
  3132.                         'path' => 'src/Controller/RdvController.php',
  3133.                         "status" => 400,
  3134.                     ])), 400);
  3135.                 }
  3136.                 // if ($publicFunction->calculScheduleFitDate($rdv->getIdCentre()->getHoraire(), $rdv->getIdAudio(), $date, $audioMotif->getDuration(), $rdv->getIdCentre()) == false) {
  3137.                 //     return new Response(json_encode(([
  3138.                 //         'message' => 'Error, no timestamp found at this time',
  3139.                 //         'path' => 'src/Controller/RdvController.php',
  3140.                 //         "status" => 400,
  3141.                 //     ])),400);
  3142.                 // }
  3143.             }
  3144.             $rdv->setDate($date);
  3145.         }
  3146.         $date $rdv->getDate();
  3147.         $smsDate $date->format('d-m-Y H:i');
  3148.         $oldDate $pastDate->format('d-m-Y H:i');
  3149.         $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>");
  3150.         return new Response(json_encode(([
  3151.             "id" => $rdv->getId(),
  3152.             "status" => 200,
  3153.         ])));
  3154.     }
  3155.     /**
  3156.      * @Route("/rdv/{id}", name="editRdvByID", methods={"PUT"})
  3157.      */
  3158.     public function editRdvByID(PublicFunction $publicFunctionRdv $rdvRequest $requestGoogleCalendarService $googleCalendarRdvSmsService $rdvSms): Response
  3159.     {
  3160.         $pastDate $rdv->getDate();
  3161.         $pastDuration $rdv->getDuration();
  3162.         $data json_decode($request->getContent(), true);
  3163.         $entityManager $this->getDoctrine()->getManager();
  3164.         if (!isset($data["token"])) {
  3165.             return new Response(json_encode([
  3166.                 "message" => "Pas de token n'a été spécifié",
  3167.                 "status" => 401,
  3168.             ]), 401);
  3169.         }
  3170.         /** @var Token */
  3171.         $token $this->getDoctrine()
  3172.             ->getRepository(Token::class)
  3173.             ->findOneBy(['token' => $data["token"]]);
  3174.         if (!$token) {
  3175.             return new Response(json_encode([
  3176.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  3177.                 "status" => 404,
  3178.             ]), 404);
  3179.         }
  3180.         // get token age
  3181.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  3182.         // if the token if older than 7 days
  3183.         if ($dateDiff->7) {
  3184.             $entityManager->remove($token);
  3185.             $entityManager->flush();
  3186.             return $this->json([
  3187.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  3188.                 'path' => 'src/Controller/ClientController.php',
  3189.                 "status" => 401,
  3190.             ], 401);
  3191.         }
  3192.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  3193.             return new Response(json_encode([
  3194.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  3195.                 "status" => 404,
  3196.             ]), 404);
  3197.         }
  3198.         if (isset($data["etat_id"])) {
  3199.             $etat $this->getDoctrine()
  3200.                 ->getRepository(EtatRdv::class)
  3201.                 ->findOneBy(['id' => $data["etat_id"]]);
  3202.             if ($etat == null) {
  3203.                 return new Response(json_encode(([
  3204.                     'message' => 'Error, no etat found at this id',
  3205.                     'path' => 'src/Controller/TrustedUserController.php',
  3206.                     "status" => 400,
  3207.                 ])), 400);
  3208.             }
  3209.             $rdv->setIdEtat($etat);
  3210.         }
  3211.         if (isset($data["audio_id"])) {
  3212.             $audio $this->getDoctrine()
  3213.                 ->getRepository(Audio::class)
  3214.                 ->findOneBy(['id' => $data["audio_id"]]);
  3215.             if ($audio == null) {
  3216.                 return new Response(json_encode(([
  3217.                     'message' => 'Error, no audio found at this id',
  3218.                     'path' => 'src/Controller/TrustedUserController.php',
  3219.                     "status" => 400,
  3220.                 ])), 400);
  3221.             }
  3222.             $rdv->setIdAudio($audio);
  3223.         }
  3224.         if (isset($data["motif_id"])) {
  3225.             $motif $this->getDoctrine()
  3226.                 ->getRepository(Motif::class)
  3227.                 ->find($data["motif_id"]);
  3228.             if ($motif == null) {
  3229.                 return new Response(json_encode(([
  3230.                     'message' => 'Error, no motif found at this id',
  3231.                     'path' => 'src/Controller/TrustedUserController.php',
  3232.                     "status" => 400,
  3233.                 ])), 400);
  3234.             }
  3235.             $rdv->setIdMotif($motif);
  3236.         }
  3237.         if (isset($data["client_id"])) {
  3238.             $client $this->getDoctrine()
  3239.                 ->getRepository(Client::class)
  3240.                 ->findOneBy(['id' => $data["client_id"]]);
  3241.             if ($client == null) {
  3242.                 return new Response(json_encode(([
  3243.                     'message' => 'Error, no client found at this id',
  3244.                     'path' => 'src/Controller/TrustedUserController.php',
  3245.                     "status" => 400,
  3246.                 ])), 400);
  3247.             }
  3248.             $rdv->setIdClient($client);
  3249.         }
  3250.         // set client status
  3251.         if (isset($data["client_status_id"])) {
  3252.             $status $this->getDoctrine()
  3253.                 ->getRepository(ClientStatus::class)
  3254.                 ->findOneBy(['id' => $data["client_status_id"]]);
  3255.             if ($status == null) {
  3256.                 return new Response(json_encode(([
  3257.                     'message' => 'Error, no status found at this id',
  3258.                     'path' => 'src/Controller/TrustedUserController.php',
  3259.                     "status" => 400,
  3260.                 ])), 400);
  3261.             }
  3262.             $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  3263.             $client->setClientStatus($status);
  3264.             $client->setLastUpdateStatus(new \DateTimeImmutable);
  3265.         }
  3266.         if (isset($data["date"])) {
  3267.             $submittedDate $data['date'] ?? null;
  3268.             $newDate \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  3269.             $currentDate $rdv->getDate();
  3270.             if (!$currentDate || $currentDate->format('d/m/Y H:i') !== $newDate->format('d/m/Y H:i')) {
  3271.                 $rdv->setDateOldRdv($currentDate);
  3272.             }
  3273.             // remove the taken schedule by rdv to make sure there is no overlap
  3274.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  3275.             $dateInput \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  3276.             $audioMotif $this->getDoctrine()
  3277.                 ->getRepository(AudioMotif::class)
  3278.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  3279.             if ($audioMotif == null) {
  3280.                 return new Response(json_encode(([
  3281.                     'message' => 'Error, no motif of this id found at this audio',
  3282.                     'path' => 'src/Controller/RdvController.php',
  3283.                     "status" => 400,
  3284.                 ])), 400);
  3285.             }
  3286.             if ($rdv->getIdAudio()->getIsIndie()) {
  3287.                 if ($rdv->getIdCentre()) {
  3288.                     // regular centre audio indie
  3289.                     /** @var AudioCentre */
  3290.                     $liaison $this->getDoctrine()
  3291.                         ->getRepository(AudioCentre::class)
  3292.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  3293.                     if ($liaison == null) {
  3294.                         return new Response(json_encode(([
  3295.                             'message' => 'Error, audio isnt part of the centre',
  3296.                             'path' => 'src/Controller/RdvController.php',
  3297.                             "status" => 400,
  3298.                         ])), 400);
  3299.                     }
  3300.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  3301.                         return new Response(json_encode(([
  3302.                             'message' => 'Error, no horaire found for this audio',
  3303.                             'path' => 'src/Controller/RdvController.php',
  3304.                             "status" => 400,
  3305.                         ])), 400);
  3306.                     }
  3307.                 } else {
  3308.                     // lieu audio indie
  3309.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  3310.                         return new Response(json_encode(([
  3311.                             'message' => 'Error, no horaire found for this audio',
  3312.                             'path' => 'src/Controller/RdvController.php',
  3313.                             "status" => 400,
  3314.                         ])), 400);
  3315.                     }
  3316.                 }
  3317.             } else {
  3318.                 // regular centre
  3319.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  3320.                     return new Response(json_encode(([
  3321.                         'message' => 'Error, no horaire found for this audio',
  3322.                         'path' => 'src/Controller/RdvController.php',
  3323.                         "status" => 400,
  3324.                     ])), 400);
  3325.                 }
  3326.             }
  3327.             $rdv->setDate($date);
  3328.         }
  3329.         if (isset($data["comment"]) && $token->getIdClient()) {
  3330.             $rdv->setComment($data["comment"]);
  3331.         }
  3332.         if (isset($data["review"]) && $token->getIdClient()) {
  3333.             $rdv->setReview($data["review"]);
  3334.         }
  3335.         if (isset($data["note"])) {
  3336.             $rdv->setNote($data["note"]);
  3337.         }
  3338.         if (isset($data["duree"])) {
  3339.             $rdv->setDuration($data["duree"]);
  3340.         }
  3341.         ////// SMSEMAIL A décommenter pour activer l'envoi de SMS + MAIL pour modification annulation de RDV, coté audio / client SMSEMAIL ////
  3342.         $date $rdv->getDate();
  3343.         $smsDate $date->format('d-m-Y H:i');
  3344.         $oldDate $pastDate->format('d-m-Y H:i');
  3345.         $locale 'fr_FR';
  3346.         $formatter = new IntlDateFormatter(
  3347.             $locale,
  3348.             IntlDateFormatter::FULL,
  3349.             IntlDateFormatter::SHORT,
  3350.             null,
  3351.             IntlDateFormatter::GREGORIAN,
  3352.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  3353.         );
  3354.         $smsDateLongFormat $formatter->format($date);
  3355.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  3356.         $frenchDate ucfirst($frenchDate);
  3357.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  3358.         // notif client
  3359.         if ($rdv->getIdEtat()->getId() != 2) {
  3360.             if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  3361.                 if ($data["sms"]) {
  3362.                     $params = array(
  3363.                         "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  3364.                         "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  3365.                         "date" => $smsDateLongFormat,
  3366.                         "heure" => substr($smsDate1115),
  3367.                         "motif" => $rdv->getIdMotif()->getTitre(),
  3368.                         "centerName" => $rdv->getIdCentre()->getName(),
  3369.                         "centerAddress" => $rdv->getIdCentre()->getAddress(),
  3370.                         "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  3371.                         "audioMail" => $rdv->getIdAudio()->getMail(),
  3372.                         "centerPhone" => $rdv->getIdCentre()->getPhone(),
  3373.                         "centerCity" => $rdv->getIdCentre()->getCity(),
  3374.                         "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  3375.                         'titre' => 'Votre rendez-vous est modifié pour le',
  3376.                         'frenchDate' => $frenchDate,
  3377.                     );
  3378.                     $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  3379.                     $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject184);
  3380.                     $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.";
  3381.                     $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  3382.                 }
  3383.             }
  3384.         }
  3385.         //     //// == suppression
  3386.         else if ($rdv->getIdEtat()->getId() == 2) {
  3387.             // delete google agenda event
  3388.             $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  3389.                 ->findBy(array('rdv' => $rdv));
  3390.             foreach ($rdvEvents as $rdvEvent) {
  3391.                 $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  3392.                 if ($googleCalendar) {
  3393.                     $googleCalendar->deleteEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId());
  3394.                     $entityManager->remove($rdvEvent);
  3395.                     $entityManager->flush();
  3396.                 }
  3397.             }
  3398.             //if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  3399.             //if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {                   
  3400.             $params = array(
  3401.                 "date" => substr($smsDate010),
  3402.                 "lien" => "{$_ENV['BASE_client']}search",
  3403.                 "heure" => substr($smsDate1115),
  3404.                 "patientName" => $client->getLastName(),
  3405.                 'titre' => 'Votre rendez-vous est annulé :',
  3406.                 'centerName' => $rdv->getIdCentre()->getName(),
  3407.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  3408.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  3409.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  3410.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  3411.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  3412.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  3413.                 'motif' => $rdv->getIdMotif()->getTitre(),
  3414.             );
  3415.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  3416.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject188);
  3417.             if ($data["sms"]) {
  3418.                 $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  3419.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  3420.             }
  3421.             //}
  3422.         }
  3423.         // set center
  3424.         if (isset($data["centre_id"])) {
  3425.             $entityManager $this->getDoctrine()->getManager();
  3426.             $centreId $data["centre_id"];
  3427.             $centre $entityManager->getRepository(Centre::class)->find($centreId);
  3428.             if (!$centre) {
  3429.                 return $this->json([
  3430.                     'message' => 'Error, no Centre found with this ID',
  3431.                     'path' => 'src/Controller/YourController.php',
  3432.                 ]);
  3433.             }
  3434.             $rdv->setIdCentre($centre);
  3435.         }
  3436.         $rdv->setGoogleAgendaImported(false);
  3437.         //notif Audio
  3438.         if ($rdv->getIdEtat()->getId() != 2) {
  3439.             if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  3440.                 if ($data["sms"]) {
  3441.                     $params = array(
  3442.                         "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  3443.                         "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  3444.                         "date" => substr($smsDate010),
  3445.                         "frenchDate" => $frenchDate,
  3446.                         "heure" => substr($smsDate1115),
  3447.                         'motif' => $rdv->getIdMotif()->getTitre(),
  3448.                         'clientPhone' => $client->getPhone(),
  3449.                         'clientNom' => $client->getLastname(),
  3450.                         'clientPrenom' => $client->getName(),
  3451.                         'clientCivilite' => $client->getCivilite(),
  3452.                         'clientPostal' => $client->getPostal(),
  3453.                         'clientMail' => $client->getMail(),
  3454.                         'centerName' => $rdv->getIdCentre()->getName(),
  3455.                         'centerPostal' => $rdv->getIdCentre()->getPostale(),
  3456.                         'centerCity' => $rdv->getIdCentre()->getCity(),
  3457.                         'centerAddress' => $rdv->getIdCentre()->getAddress(),
  3458.                         'idPatient' => $client->getId(),
  3459.                         'proUrl' => "{$_ENV['BASE_logiciel']}",
  3460.                         'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  3461.                         'titre' => 'Votre rendez-vous est modifié pour le :'
  3462.                     );
  3463.                     $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  3464.                     $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  3465.                     if ($rdv->getIdAudio()->getModifRdvMail()) {
  3466.                         $subject "🔀 Rendez-vous My Audio modifié du " $frenchDate " à " substr($smsDate1115);
  3467.                         $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject186);
  3468.                     }
  3469.                     if ($rdv->getIdAudio()->getModifRdvSms()) {
  3470.                         // we ignore the sms send to the audio for the case he modify the rdv (so lets commented)
  3471.                         $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.";
  3472.                         //$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $phoneAudio);
  3473.                     }
  3474.                 }
  3475.             }
  3476.         } else if ($rdv->getIdEtat()->getId() == 2) {
  3477.             if ($data["sms"]) {
  3478.                 $params = array(
  3479.                     "date" => substr($smsDate010),
  3480.                     "lien" => "{$_ENV['BASE_client']}search",
  3481.                     "heure" => substr($smsDate1115),
  3482.                     "patientName" => $client->getLastName(),
  3483.                     'titre' => 'Votre rendez-vous est annulé :',
  3484.                     'centerName' => $rdv->getIdCentre()->getName(),
  3485.                     'centerPostal' => $rdv->getIdCentre()->getPostale(),
  3486.                     'centerCity' => $rdv->getIdCentre()->getCity(),
  3487.                     'centerAddress' => $rdv->getIdCentre()->getAddress(),
  3488.                     'centerPhone' => $rdv->getIdCentre()->getPhone(),
  3489.                     'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  3490.                     'audioMail' => $rdv->getIdAudio()->getMail(),
  3491.                     'motif' => $rdv->getIdMotif()->getTitre(),
  3492.                 );
  3493.                 $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  3494.                 $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  3495.                 if ($rdv->getIdAudio()->getModifRdvMail()) {
  3496.                     $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  3497.                     $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject188);
  3498.                 }
  3499.                 if ($rdv->getIdAudio()->getModifRdvSms()) {
  3500.                     $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.";
  3501.                     // $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $phoneAudio);
  3502.                 }
  3503.             }
  3504.         }
  3505.         $entityManager->flush();
  3506.         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"]))) {
  3507.             if (is_null($rdv->getIdClientTemp())) {
  3508.                 $clientRDV $this->getDoctrine()
  3509.                     ->getRepository(Client::class)
  3510.                     ->findOneBy(['id' => $rdv->getIdClient()->getId()]);
  3511.                 $clientRDV->setName($data["prenom_patient"]);
  3512.                 $clientRDV->setLastname($data["nom_patient"]);
  3513.                 $clientRDV->setMail($data["mail_patient"]);
  3514.                 $clientRDV->setPhone($data["portable_patient"]);
  3515.                 $clientRDV->setPhoneFixe($data["fixe_patient"]);
  3516.             } else {
  3517.                 $clientRDV $this->getDoctrine()
  3518.                     ->getRepository(ClientTemp::class)
  3519.                     ->findOneBy(['id' => $rdv->getIdClientTemp()->getId()]);
  3520.                 $clientRDV->setName($data["prenom_patient"]);
  3521.                 $clientRDV->setLastname($data["nom_patient"]);
  3522.                 $clientRDV->setMail($data["mail_patient"]);
  3523.                 $clientRDV->setPhone($data["portable_patient"]);
  3524.                 $clientRDV->setPhoneFixe($data["fixe_patient"]);
  3525.             }
  3526.             if (!empty($data["birthday_patient"])) {
  3527.                 $birth \DateTime::createFromFormat("Y-m-d"$data["birthday_patient"]);
  3528.                 $clientRDV->setBirthdate($birth);
  3529.             }
  3530.             $entityManager->flush();
  3531.         }
  3532.         if (is_null($rdv->getIdClient())) {
  3533.             $prenom_patient $rdv->getIdClientTemp()->getName();
  3534.             $nom_patient $rdv->getIdClientTemp()->getLastname();
  3535.             $mail_patient $rdv->getIdClientTemp()->getMail();
  3536.             $portable_patient $rdv->getIdClientTemp()->getPhone();
  3537.             $fixe_patient $rdv->getIdClientTemp()->getPhoneFixe();
  3538.             $birthday $rdv->getIdClientTemp()->getBirthdate();
  3539.         } elseif (is_null($rdv->getIdClientTemp())) {
  3540.             $prenom_patient =  $rdv->getIdClient()->getName();
  3541.             $nom_patient $rdv->getIdClient()->getLastname();
  3542.             $mail_patient $rdv->getIdClient()->getMail();
  3543.             $portable_patient $rdv->getIdClient()->getPhone();
  3544.             $fixe_patient $rdv->getIdClient()->getPhoneFixe();
  3545.             $birthday $rdv->getIdClient()->getBirthdate();
  3546.         } else {
  3547.             $prenom_patient "";
  3548.             $nom_patient "";
  3549.             $mail_patient "";
  3550.             $portable_patient "";
  3551.             $fixe_patient "";
  3552.             $birthday "";
  3553.         }
  3554.         /* generate sms notif on update */
  3555.         // update sms notification     
  3556.         $rdvSms->updateRdvSms($rdv);
  3557.         // google calendar update
  3558.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  3559.             ->findBy(array('audio' => $rdv->getIdAudio()));
  3560.         $data['rdv'] = $rdv->getId();
  3561.         if ($rdv->getIdClient() !== null) {
  3562.             $data["client_id"] = $rdv->getIdClient()->getId();
  3563.         }
  3564.         if ($rdv->getIdClientTemp() !== null) {
  3565.             $data["client_id_temp"] = $rdv->getIdClientTemp()->getId();
  3566.         }
  3567.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  3568.             ->findBy(array('rdv' => $rdv));
  3569.         foreach ($rdvEvents as $rdvEvent) {
  3570.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  3571.             $googleCalendar->updateEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
  3572.         }
  3573.         $synchronisationCosium $this->getDoctrine()->getRepository(SynchronisationCosium::class)->findOneBy(["audio" => $rdv->getIdAudio()->getId()]);
  3574.         $cosiumCenter $this->getDoctrine()->getRepository(CosiumCenter::class)->findOneBy(["synchronisationCosium" => $synchronisationCosium"center" => $rdv->getIdCentre()]);
  3575.         if ($cosiumCenter) {
  3576.             $this->clientCosiumService->deleteRdv($synchronisationCosium$rdv);
  3577.             $this->clientCosiumService->createAgenda($synchronisationCosium$rdv$cosiumCenter);
  3578.         }
  3579.         return new Response(json_encode(([
  3580.             "id" => $rdv->getId(),
  3581.             "motif_id" => $rdv->getIdMotif()->getId(),
  3582.             "motif_libelle" => $rdv->getIdMotif()->getTitre(),
  3583.             "audio_id" => $rdv->getIdAudio()->getId(),
  3584.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  3585.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  3586.             "fullName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  3587.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  3588.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  3589.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  3590.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  3591.             "centre_name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : null,
  3592.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  3593.             "etat_id" => $rdv->getIdEtat()->getId(),
  3594.             "date" => $rdv->getDate(),
  3595.             "comment" => $rdv->getComment(),
  3596.             "note" => $rdv->getNote(),
  3597.             "review" => $rdv->getReview(),
  3598.             "clientEtatId" => $client->getClientStatus() ? $client->getClientStatus()->getId() : 0,
  3599.             "prenom_patient" => $prenom_patient,
  3600.             "nom_patient" => $nom_patient,
  3601.             "mail_patient" => $mail_patient,
  3602.             "portable_patient" => $portable_patient,
  3603.             "fixe_patient" => $fixe_patient,
  3604.             "birthday" => $birthday,
  3605.             "status" => 200,
  3606.         ])));
  3607.     }
  3608.     /**
  3609.      * @Route("/rdv-by-patient/{id}", name="editRdvByIDFromPatient", methods={"PUT"})
  3610.      */
  3611.     public function editRdvByIDFromPatient(PublicFunction $publicFunctionRdv $rdvRequest $request): Response
  3612.     {
  3613.         $pastDate $rdv->getDate();
  3614.         $pastDuration $rdv->getDuration();
  3615.         $data json_decode($request->getContent(), true);
  3616.         $entityManager $this->getDoctrine()->getManager();
  3617.         if (!isset($data["token"])) {
  3618.             return new Response(json_encode([
  3619.                 "message" => "Pas de token n'a été spécifié",
  3620.                 "status" => 401,
  3621.             ]), 401);
  3622.         }
  3623.         /** @var Token */
  3624.         $token $this->getDoctrine()
  3625.             ->getRepository(Token::class)
  3626.             ->findOneBy(['token' => $data["token"]]);
  3627.         if (!$token) {
  3628.             return new Response(json_encode([
  3629.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  3630.                 "status" => 404,
  3631.             ]), 404);
  3632.         }
  3633.         // get token age
  3634.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  3635.         // if the token if older than 7 days
  3636.         if ($dateDiff->7) {
  3637.             $entityManager->remove($token);
  3638.             $entityManager->flush();
  3639.             return $this->json([
  3640.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  3641.                 'path' => 'src/Controller/ClientController.php',
  3642.                 "status" => 401,
  3643.             ], 401);
  3644.         }
  3645.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  3646.             return new Response(json_encode([
  3647.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  3648.                 "status" => 404,
  3649.             ]), 404);
  3650.         }
  3651.         if (isset($data["etat_id"])) {
  3652.             $etat $this->getDoctrine()
  3653.                 ->getRepository(EtatRdv::class)
  3654.                 ->findOneBy(['id' => $data["etat_id"]]);
  3655.             if ($etat == null) {
  3656.                 return new Response(json_encode(([
  3657.                     'message' => 'Error, no etat found at this id',
  3658.                     'path' => 'src/Controller/TrustedUserController.php',
  3659.                     "status" => 400,
  3660.                 ])), 400);
  3661.             }
  3662.             $rdv->setIdEtat($etat);
  3663.         }
  3664.         if (isset($data["audio_id"])) {
  3665.             $audio $this->getDoctrine()
  3666.                 ->getRepository(Audio::class)
  3667.                 ->findOneBy(['id' => $data["audio_id"]]);
  3668.             if ($audio == null) {
  3669.                 return new Response(json_encode(([
  3670.                     'message' => 'Error, no audio found at this id',
  3671.                     'path' => 'src/Controller/TrustedUserController.php',
  3672.                     "status" => 400,
  3673.                 ])), 400);
  3674.             }
  3675.             $rdv->setIdAudio($audio);
  3676.         }
  3677.         if (isset($data["motif_id"])) {
  3678.             $motif $this->getDoctrine()
  3679.                 ->getRepository(Motif::class)
  3680.                 ->find($data["motif_id"]);
  3681.             if ($motif == null) {
  3682.                 return new Response(json_encode(([
  3683.                     'message' => 'Error, no motif found at this id',
  3684.                     'path' => 'src/Controller/TrustedUserController.php',
  3685.                     "status" => 400,
  3686.                 ])), 400);
  3687.             }
  3688.             $rdv->setIdMotif($motif);
  3689.         }
  3690.         if (isset($data["client_id"])) {
  3691.             $client $this->getDoctrine()
  3692.                 ->getRepository(Client::class)
  3693.                 ->findOneBy(['id' => $data["client_id"]]);
  3694.             if ($client == null) {
  3695.                 return new Response(json_encode(([
  3696.                     'message' => 'Error, no client found at this id',
  3697.                     'path' => 'src/Controller/TrustedUserController.php',
  3698.                     "status" => 400,
  3699.                 ])), 400);
  3700.             }
  3701.             $rdv->setIdClient($client);
  3702.         }
  3703.         if (isset($data["date"])) {
  3704.             // remove the taken schedule by rdv to make sure there is no overlap
  3705.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  3706.             $dateInput \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  3707.             $audioMotif $this->getDoctrine()
  3708.                 ->getRepository(AudioMotif::class)
  3709.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  3710.             if ($audioMotif == null) {
  3711.                 return new Response(json_encode(([
  3712.                     'message' => 'Error, no motif of this id found at this audio',
  3713.                     'path' => 'src/Controller/RdvController.php',
  3714.                     "status" => 400,
  3715.                 ])), 400);
  3716.             }
  3717.             if ($rdv->getIdAudio()->getIsIndie()) {
  3718.                 if ($rdv->getIdCentre()) {
  3719.                     // regular centre audio indie
  3720.                     /** @var AudioCentre */
  3721.                     $liaison $this->getDoctrine()
  3722.                         ->getRepository(AudioCentre::class)
  3723.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  3724.                     if ($liaison == null) {
  3725.                         return new Response(json_encode(([
  3726.                             'message' => 'Error, audio isnt part of the centre',
  3727.                             'path' => 'src/Controller/RdvController.php',
  3728.                             "status" => 400,
  3729.                         ])), 400);
  3730.                     }
  3731.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  3732.                         return new Response(json_encode(([
  3733.                             'message' => 'Error, no horaire found for this audio',
  3734.                             'path' => 'src/Controller/RdvController.php',
  3735.                             "status" => 400,
  3736.                         ])), 400);
  3737.                     }
  3738.                 } else {
  3739.                     // lieu audio indie
  3740.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  3741.                         return new Response(json_encode(([
  3742.                             'message' => 'Error, no horaire found for this audio',
  3743.                             'path' => 'src/Controller/RdvController.php',
  3744.                             "status" => 400,
  3745.                         ])), 400);
  3746.                     }
  3747.                 }
  3748.             } else {
  3749.                 // regular centre
  3750.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  3751.                     return new Response(json_encode(([
  3752.                         'message' => 'Error, no horaire found for this audio',
  3753.                         'path' => 'src/Controller/RdvController.php',
  3754.                         "status" => 400,
  3755.                     ])), 400);
  3756.                 }
  3757.             }
  3758.             $rdv->setDate($date);
  3759.         }
  3760.         if (isset($data["comment"]) && $token->getIdClient()) {
  3761.             $rdv->setComment($data["comment"]);
  3762.         }
  3763.         if (isset($data["review"]) && $token->getIdClient()) {
  3764.             $rdv->setReview($data["review"]);
  3765.         }
  3766.         if (isset($data["note"])) {
  3767.             $rdv->setNote($data["note"]);
  3768.         }
  3769.         if (isset($data["duree"])) {
  3770.             $rdv->setDuration($data["duree"]);
  3771.         }
  3772.         ////// SMSEMAIL A décommenter pour activer l'envoi de SMS + MAIL pour modification annulation de RDV, coté audio / client SMSEMAIL ////
  3773.         $date $rdv->getDate();
  3774.         $smsDate $date->format('d-m-Y H:i');
  3775.         $oldDate $pastDate->format('d-m-Y H:i');
  3776.         $locale 'fr_FR';
  3777.         $formatter = new IntlDateFormatter(
  3778.             $locale,
  3779.             IntlDateFormatter::FULL,
  3780.             IntlDateFormatter::SHORT,
  3781.             null,
  3782.             IntlDateFormatter::GREGORIAN,
  3783.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  3784.         );
  3785.         $smsDateLongFormat $formatter->format($date);
  3786.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  3787.         $frenchDate ucfirst($frenchDate);
  3788.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  3789.         // notif client
  3790.         if ($rdv->getIdEtat()->getId() != 2) {
  3791.             if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  3792.                 $params = array(
  3793.                     "lienModifier" => "{$_ENV['BASE_client']}mes-rendez-vous",
  3794.                     "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  3795.                     "date" => $smsDateLongFormat,
  3796.                     "heure" => substr($smsDate1115),
  3797.                     "motif" => $rdv->getIdMotif()->getTitre(),
  3798.                     "centerName" => $rdv->getIdCentre()->getName(),
  3799.                     "centerAddress" => $rdv->getIdCentre()->getAddress(),
  3800.                     "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  3801.                     "audioMail" => $rdv->getIdAudio()->getMail(),
  3802.                     "centerPhone" => $rdv->getIdCentre()->getPhone(),
  3803.                     "centerCity" => $rdv->getIdCentre()->getCity(),
  3804.                     "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  3805.                     'titre' => 'Votre rendez-vous est modifié pour le',
  3806.                     'frenchDate' => $frenchDate,
  3807.                 );
  3808.                 $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  3809.                 $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject184);
  3810.                 $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.";
  3811.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  3812.             }
  3813.         }
  3814.         //     //// == suppression
  3815.         else if ($rdv->getIdEtat()->getId() == 2) {
  3816.             //if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  3817.             //if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {                   
  3818.             $params = array(
  3819.                 "date" => substr($smsDate010),
  3820.                 "lien" => "{$_ENV['BASE_client']}audioprothesiste/{$rdv->getIdCentre()->getCity()}/{$rdv->getIdCentre()->getPostale()}/{$rdv->getIdCentre()->getName()}/prise-de-rdv-audioprothesiste-rapide/{$rdv->getIdCentre()->getId()}",
  3821.                 "heure" => substr($smsDate1115),
  3822.                 "patientName" => $client->getLastName(),
  3823.                 'titre' => 'Votre rendez-vous est annulé :',
  3824.                 'centerName' => $rdv->getIdCentre()->getName(),
  3825.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  3826.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  3827.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  3828.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  3829.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  3830.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  3831.                 'motif' => $rdv->getIdMotif()->getTitre(),
  3832.             );
  3833.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  3834.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject203);
  3835.             $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  3836.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  3837.             //}
  3838.         }
  3839.         // set center
  3840.         if (isset($data["centre_id"])) {
  3841.             $entityManager $this->getDoctrine()->getManager();
  3842.             $centreId $data["centre_id"];
  3843.             $centre $entityManager->getRepository(Centre::class)->find($centreId);
  3844.             if (!$centre) {
  3845.                 return $this->json([
  3846.                     'message' => 'Error, no Centre found with this ID',
  3847.                     'path' => 'src/Controller/YourController.php',
  3848.                 ]);
  3849.             }
  3850.             $rdv->setIdCentre($centre);
  3851.         }
  3852.         $rdv->setGoogleAgendaImported(false);
  3853.         //notif Audio
  3854.         if ($rdv->getIdEtat()->getId() != 2) {
  3855.             if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  3856.                 $params = array(
  3857.                     "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  3858.                     "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  3859.                     "date" => $pastDate->format("y-m-d"),
  3860.                     "heure" => $pastDate->format("H:i"),
  3861.                     'clientPhone' => $client->getPhone(),
  3862.                     'clientCivilite' => $client->getCivilite(),
  3863.                     'clientNom' => $client->getLastname(),
  3864.                     'clientPrenom' => $client->getName(),
  3865.                     'clientPostal' => $client->getPostal(),
  3866.                     'clientMail' => $client->getMail(),
  3867.                     "birthdate" => $rdv->getIdClient()->getBirthdate()->format("y-m-d"),
  3868.                     "mail" => $rdv->getIdClient()->getMail(),
  3869.                     "phone" => $rdv->getIdClient()->getPhone(),
  3870.                     "motif" => $rdv->getIdMotif()->getTitre(),
  3871.                     "address" => $rdv->getIdCentre()->getAddress(),
  3872.                     "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getLastName() . ' ' $rdv->getIdAudio()->getName(),
  3873.                     "newRdvDate" => substr($smsDate010),
  3874.                     "newRdvHour" => substr($smsDate1115),
  3875.                     "centerName" => $rdv->getIdCentre()->getName(),
  3876.                     "centerAddress" => $rdv->getIdCentre()->getAddress(),
  3877.                     "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  3878.                     'titre' => "Modification de Rendez-vous My Audio de {$rdv->getIdClient()->getLastname()}",
  3879.                     "urlPro" => "{$_ENV['BASE_logiciel']}",
  3880.                     "idPatient" => $rdv->getIdClient()->getId(),
  3881.                 );
  3882.                 $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  3883.                 $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  3884.                 if ($rdv->getIdAudio()->getModifRdvMail()) {
  3885.                     $subject "🔀 Rendez-vous My Audio modifié par " $client->getCivilite() . " " $client->getName() . " " $client->getLastname();
  3886.                     $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject185);
  3887.                 }
  3888.                 $subjectMyAudio "🔀 Le patient " $client->getCivilite() . " " $client->getName() . " " $client->getLastname() . "  a modifié son rendez-vous My Audio";
  3889.                 $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subjectMyAudio204);
  3890.                 if ($rdv->getIdAudio()->getModifRdvSms()) {
  3891.                     $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.";
  3892.                     $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  3893.                 }
  3894.             }
  3895.         } else if ($rdv->getIdEtat()->getId() == 2) {
  3896.             $params = array(
  3897.                 "date" => substr($smsDate010),
  3898.                 "heure" => substr($smsDate1115),
  3899.                 "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  3900.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  3901.                 "motif" => $rdv->getIdMotif()->getTitre(),
  3902.                 "centerAddress" => $rdv->getIdCentre()->getAddress(),
  3903.                 "centerPostal" => $rdv->getIdCentre()->getPostale(),
  3904.                 "centerCity" => $rdv->getIdCentre()->getCity(),
  3905.                 "centerName" => $rdv->getIdCentre()->getName(),
  3906.                 "clientNom" => $rdv->getIdClient()->getLastname(),
  3907.                 "clientPrenom" => $rdv->getIdClient()->getName(),
  3908.                 "clientMail" => $rdv->getIdClient()->getMail(),
  3909.                 "clientPhone" => $rdv->getIdClient()->getPhone(),
  3910.                 'titre' => "Annulation du Rendez-vous avec le patient {$rdv->getIdClient()->getLastname()}",
  3911.                 "proUrl" => "{$_ENV['BASE_logiciel']}",
  3912.                 "idPatient" => $rdv->getIdClient()->getId(),
  3913.             );
  3914.             $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  3915.             $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  3916.             if ($rdv->getIdAudio()->getModifRdvMail()) {
  3917.                 $subject "❌ Annulation du rendez-vous par le patient " $client->getCivilite() . " " $client->getName() . " " $client->getLastname();
  3918.                 $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject187);
  3919.             }
  3920.             $subject "❌ Annulation du rendez-vous par le patient " $client->getCivilite() . " " $client->getName() . " " $client->getLastname();
  3921.             $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject195);
  3922.             if ($rdv->getIdAudio()->getModifRdvSms()) {
  3923.                 $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.";
  3924.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  3925.             }
  3926.         }
  3927.         $entityManager->flush();
  3928.         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"]))) {
  3929.             $birth \DateTime::createFromFormat("Y-m-d"$data["birthday_patient"]);
  3930.             if (is_null($rdv->getIdClientTemp())) {
  3931.                 $clientRDV $this->getDoctrine()
  3932.                     ->getRepository(Client::class)
  3933.                     ->findOneBy(['id' => $rdv->getIdClient()->getId()]);
  3934.                 $clientRDV->setName($data["prenom_patient"]);
  3935.                 $clientRDV->setLastname($data["nom_patient"]);
  3936.                 $clientRDV->setBirthdate($birth);
  3937.                 $clientRDV->setMail($data["mail_patient"]);
  3938.                 $clientRDV->setPhone($data["portable_patient"]);
  3939.                 $clientRDV->setPhoneFixe($data["fixe_patient"]);
  3940.             } else {
  3941.                 $clientRDV $this->getDoctrine()
  3942.                     ->getRepository(ClientTemp::class)
  3943.                     ->findOneBy(['id' => $rdv->getIdClientTemp()->getId()]);
  3944.                 $clientRDV->setName($data["prenom_patient"]);
  3945.                 $clientRDV->setLastname($data["nom_patient"]);
  3946.                 $clientRDV->setBirthdate($birth);
  3947.                 $clientRDV->setMail($data["mail_patient"]);
  3948.                 $clientRDV->setPhone($data["portable_patient"]);
  3949.                 $clientRDV->setPhoneFixe($data["fixe_patient"]);
  3950.             }
  3951.             $entityManager->flush();
  3952.         }
  3953.         if (is_null($rdv->getIdClient())) {
  3954.             $prenom_patient $rdv->getIdClientTemp()->getName();
  3955.             $nom_patient $rdv->getIdClientTemp()->getLastname();
  3956.             $mail_patient $rdv->getIdClientTemp()->getMail();
  3957.             $portable_patient $rdv->getIdClientTemp()->getPhone();
  3958.             $fixe_patient $rdv->getIdClientTemp()->getPhoneFixe();
  3959.             $birthday $rdv->getIdClientTemp()->getBirthdate();
  3960.         } elseif (is_null($rdv->getIdClientTemp())) {
  3961.             $prenom_patient =  $rdv->getIdClient()->getName();
  3962.             $nom_patient $rdv->getIdClient()->getLastname();
  3963.             $mail_patient $rdv->getIdClient()->getMail();
  3964.             $portable_patient $rdv->getIdClient()->getPhone();
  3965.             $fixe_patient $rdv->getIdClient()->getPhoneFixe();
  3966.             $birthday $rdv->getIdClient()->getBirthdate();
  3967.         } else {
  3968.             $prenom_patient "";
  3969.             $nom_patient "";
  3970.             $mail_patient "";
  3971.             $portable_patient "";
  3972.             $fixe_patient "";
  3973.             $birthday "";
  3974.         }
  3975.         return new Response(json_encode(([
  3976.             "id" => $rdv->getId(),
  3977.             "motif_id" => $rdv->getIdMotif()->getId(),
  3978.             "motif_libelle" => $rdv->getIdMotif()->getTitre(),
  3979.             "audio_id" => $rdv->getIdAudio()->getId(),
  3980.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  3981.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  3982.             "fullName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  3983.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  3984.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  3985.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  3986.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  3987.             "centre_name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : null,
  3988.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  3989.             "etat_id" => $rdv->getIdEtat()->getId(),
  3990.             "date" => $rdv->getDate(),
  3991.             "comment" => $rdv->getComment(),
  3992.             "note" => $rdv->getNote(),
  3993.             "review" => $rdv->getReview(),
  3994.             "prenom_patient" => $prenom_patient,
  3995.             "nom_patient" => $nom_patient,
  3996.             "mail_patient" => $mail_patient,
  3997.             "portable_patient" => $portable_patient,
  3998.             "fixe_patient" => $fixe_patient,
  3999.             "birthday" => $birthday,
  4000.             "status" => 200,
  4001.         ])));
  4002.     }
  4003.     /**
  4004.      * @Route("/rdv/{id}/supp", name="suppRdvByID", methods={"PUT"})
  4005.      */
  4006.     public function suppRdvByID(PublicFunction $publicFunctionRdv $rdvRequest $requestGoogleCalendarService $googleCalendarRdvSmsService $rdvSms): Response
  4007.     {
  4008.         $pastDate $rdv->getDate();
  4009.         $data json_decode($request->getContent(), true);
  4010.         $entityManager $this->getDoctrine()->getManager();
  4011.         if (!isset($data["token"])) {
  4012.             return new Response(json_encode([
  4013.                 "message" => "Pas de token n'a été spécifié",
  4014.                 "status" => 401,
  4015.             ]), 401);
  4016.         }
  4017.         /** @var Token */
  4018.         $token $this->getDoctrine()
  4019.             ->getRepository(Token::class)
  4020.             ->findOneBy(['token' => $data["token"]]);
  4021.         if (!$token) {
  4022.             return new Response(json_encode([
  4023.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  4024.                 "status" => 404,
  4025.             ]), 404);
  4026.         }
  4027.         // get token age
  4028.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  4029.         // if the token if older than 7 days
  4030.         if ($dateDiff->7) {
  4031.             $entityManager->remove($token);
  4032.             $entityManager->flush();
  4033.             return $this->json([
  4034.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  4035.                 'path' => 'src/Controller/ClientController.php',
  4036.                 "status" => 401,
  4037.             ], 401);
  4038.         }
  4039.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  4040.             return new Response(json_encode([
  4041.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  4042.                 "status" => 404,
  4043.             ]), 404);
  4044.         }
  4045.         // delete google agenda event
  4046.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  4047.             ->findBy(array('rdv' => $rdv));
  4048.         //dd($rdvEvents);
  4049.         $synchronisationCosium $this->getDoctrine()->getRepository(SynchronisationCosium::class)->findOneBy(["audio" => $rdv->getIdAudio()->getId()]);
  4050.         $cosiumCenter $this->getDoctrine()->getRepository(CosiumCenter::class)->findBy(["synchronisationCosium" => $synchronisationCosium"center" => $rdv->getIdCentre()]);
  4051.         if ($cosiumCenter) {
  4052.             $this->clientCosiumService->deleteRdv($synchronisationCosium$rdv);
  4053.         }
  4054.         foreach ($rdvEvents as $rdvEvent) {
  4055.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  4056.             $googleCalendar->deleteEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId());
  4057.             $entityManager->remove($rdvEvent);
  4058.             $entityManager->flush();
  4059.         }
  4060.         $etat $this->getDoctrine()
  4061.             ->getRepository(EtatRdv::class)
  4062.             ->findOneBy(['id' => 2]);
  4063.         if ($etat == null) {
  4064.             return new Response(json_encode(([
  4065.                 'message' => 'Error, no etat found at this id',
  4066.                 'path' => 'src/Controller/TrustedUserController.php',
  4067.                 "status" => 400,
  4068.             ])), 400);
  4069.         }
  4070.         $rdv->setIdEtat($etat);
  4071.         $rdv->setCacher(1);
  4072.         ////// SMSEMAIL A décommenter pour activer l'envoi de SMS + MAIL pour modification annulation de RDV, coté audio / client SMSEMAIL ////
  4073.         $date $rdv->getDate();
  4074.         $smsDate $date->format('d-m-Y H:i');
  4075.         $oldDate $pastDate->format('d-m-Y H:i');
  4076.         $locale 'fr_FR';
  4077.         $formatter = new IntlDateFormatter(
  4078.             $locale,
  4079.             IntlDateFormatter::FULL,
  4080.             IntlDateFormatter::SHORT,
  4081.             null,
  4082.             IntlDateFormatter::GREGORIAN,
  4083.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  4084.         );
  4085.         $smsDateLongFormat $formatter->format($date);
  4086.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  4087.         $frenchDate ucfirst($frenchDate);
  4088.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  4089.         // notif client
  4090.         if ($rdv->getIdEtat()->getId() != 2) {
  4091.             $params = array(
  4092.                 "lienModifier" => "{$_ENV['BASE_client']}mes-rendez-vous",
  4093.                 "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  4094.                 "date" => $smsDateLongFormat,
  4095.                 "heure" => substr($smsDate1115),
  4096.                 "motif" => $rdv->getIdMotif()->getTitre(),
  4097.                 "centerName" => $rdv->getIdCentre()->getName(),
  4098.                 "centerAddress" => $rdv->getIdCentre()->getAddress(),
  4099.                 "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  4100.                 "audioMail" => $rdv->getIdAudio()->getMail(),
  4101.                 "centerPhone" => $rdv->getIdCentre()->getPhone(),
  4102.                 "centerCity" => $rdv->getIdCentre()->getCity(),
  4103.                 "clientEmail" => $client->getMail(),
  4104.                 "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  4105.                 'titre' => 'Votre rendez-vous est modifié pour le',
  4106.                 'frenchDate' => $frenchDate
  4107.             );
  4108.             $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  4109.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject205);
  4110.             $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.";
  4111.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  4112.             // creer un mail de notif pour myAudio + créé le template LP | MA | RR - Modification du RDV - Centre Auditif - MyAudio
  4113.             $subjectMyaudio "Rendez-vous My Audio a été modifié par l'audioprothésiste " $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName();
  4114.             $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$client->getName() . ' ' $client->getLastName(), $subjectMyaudio206);
  4115.         }
  4116.         //     //// == suppression
  4117.         else if ($rdv->getIdEtat()->getId() == 2) {
  4118.             $params = array(
  4119.                 "date" => substr($smsDate010),
  4120.                 "lien" => "{$_ENV['BASE_client']}search",
  4121.                 "heure" => substr($smsDate1115),
  4122.                 "patientName" => $client->getLastName() . ' ' $client->getName(),
  4123.                 'titre' => 'Votre rendez-vous est annulé :',
  4124.                 'centerName' => $rdv->getIdCentre()->getName(),
  4125.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4126.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  4127.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4128.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  4129.                 "clientEmail" => $client->getMail() ?? '',
  4130.                 "clientPhone" => $client->getPhone() ?? '',
  4131.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  4132.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  4133.                 'motif' => $rdv->getIdMotif()->getTitre(),
  4134.             );
  4135.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  4136.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject188);
  4137.             $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  4138.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  4139.             // creer un mail de notif pour myAudio + créé le template LP | MA | RR - Annlation du RDV - Centre Auditif - MyAudio
  4140.             $subjectMyaudio $rdv->getIdCentre()->getName() . " a annulé un rendez-vous My Audio avec " $client->getName() . ' ' $client->getLastName();
  4141.             $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$client->getName() . ' ' $client->getLastName(), $subjectMyaudio207);
  4142.         }
  4143.         //notif Audio
  4144.         if ($rdv->getIdEtat()->getId() != 2) {
  4145.             $params = array(
  4146.                 "lienModifier" => "{$_ENV['BASE_logiciel']}rdv",
  4147.                 "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  4148.                 "date" => substr($smsDate010),
  4149.                 "frenchDate" => $frenchDate,
  4150.                 "heure" => substr($smsDate1115),
  4151.                 'motif' => $rdv->getIdMotif()->getTitre(),
  4152.                 'clientPhone' => $client->getPhone(),
  4153.                 'clientNom' => $client->getLastname(),
  4154.                 'clientPrenom' => $client->getName(),
  4155.                 'clientCivilite' => $client->getCivilite(),
  4156.                 'clientPostal' => $client->getPostal(),
  4157.                 'clientMail' => $client->getMail(),
  4158.                 'centerName' => $rdv->getIdCentre()->getName(),
  4159.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4160.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  4161.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4162.                 'idPatient' => $client->getId(),
  4163.                 'proUrl' => "{$_ENV['BASE_logiciel']}",
  4164.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  4165.                 'titre' => 'Votre rendez-vous est modifié pour le :'
  4166.             );
  4167.             $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  4168.             $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  4169.             if ($rdv->getIdAudio()->getModifRdvMail()) {
  4170.                 $subject "🔀 Rendez-vous My Audio modifié du " $frenchDate " à " substr($smsDate1115);
  4171.                 $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject186);
  4172.             }
  4173.             if ($rdv->getIdAudio()->getModifRdvSms()) {
  4174.                 $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.";
  4175.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  4176.             }
  4177.         } else if ($rdv->getIdEtat()->getId() == 2) {
  4178.             /* $params = array(  
  4179.                     "date" => substr($smsDate, 0, 10),
  4180.                     "lien"=> "{$_ENV['BASE_client']}search",
  4181.                     "heure" =>substr($smsDate, 11, 15),
  4182.                     "patientName" => $client->getLastName(),
  4183.                     'titre' => 'Votre rendez-vous est annulé :',
  4184.                     'centerName' => $rdv->getIdCentre()->getName(),
  4185.                     'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4186.                     'centerCity' => $rdv->getIdCentre()->getCity(),
  4187.                     'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4188.                     'centerPhone' => $rdv->getIdCentre()->getPhone(),
  4189.                     'audioproName' => $rdv->getIdAudio()->getCivilite().' '. $rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(),                    
  4190.                     'audioMail' => $rdv->getIdAudio()->getMail(),
  4191.                     'motif' => $rdv->getIdMotif()->getTitre(),
  4192.                 );
  4193.                 $subject = "Rendez-vous My Audio annulé avec " . $rdv->getIdCentre()->getName();
  4194.                 $publicFunction->sendEmail($params, $rdv->getIdAudio()->getMail(), $rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(), $subject, 188 );
  4195.                 $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.";
  4196.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $rdv->getIdAudio()->getPhone());
  4197.                 */
  4198.         }
  4199.         // delete sms notification     
  4200.         $rdvSms->deleteAssociatedRdvSms($rdv);
  4201.         // delete client device
  4202.         /*$clientDevice = $this->getDoctrine()->getRepository(ClientDevice::class)->findOneBy(['rdv' => $rdv]);
  4203. if($clientDevice)
  4204. {
  4205. if ($client instanceof Client) {
  4206.     $nextRdvs = $this->getDoctrine()
  4207.         ->getRepository(Rdv::class)
  4208.         ->findBy([
  4209.             "id_client" => $rdv->getIdClient(),
  4210.             "id_motif" => ['106', '107', '108', '109'] 
  4211.         ]);
  4212.         $client->setClientStatus(null);
  4213. } elseif ($client instanceof ClientTemp) {
  4214.  $nextRdvs = $this->getDoctrine()
  4215.         ->getRepository(Rdv::class)
  4216.         ->findBy([
  4217.             "id_client_temp" => $rdv->getIdClientTemp(),
  4218.             "id_motif" => ['106', '107', '108', '109'] 
  4219.         ]);
  4220.         $client->setClientStatus(null);
  4221.     } 
  4222.     $locale = 'fr_FR';
  4223.     $fmt = new IntlDateFormatter($locale, IntlDateFormatter::FULL, IntlDateFormatter::NONE);
  4224.     $fmt->setPattern("EEEE dd MMMM yyyy"); 
  4225.     if($nextRdvs){
  4226.     $params = array(  
  4227.                 "title" => "Affectation de votre appareil et programmation de vos rendez-vous",
  4228.                 "centerName" => "{$rdv->getIdCentre()->getName()}",
  4229.                 "audioName" => "{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastName()}",
  4230.                 "centerAddress" => "{$rdv->getIdCentre()->getAddress()}",
  4231.                 "device" => "{$clientDevice->getDevice()->getModel()}",
  4232.                 "ears" => "{$clientDevice->getSettingDevice()->getName()}",
  4233.                 "rdvOneDate" => "{$fmt->format($nextRdvs['0']->getDate())}",
  4234.                 "rdvOneHour" => "{$nextRdvs['0']->getDate()->format('H:i')}",
  4235.                 "rdvTwoDate" => "{$fmt->format($nextRdvs['1']->getDate())}",
  4236.                 "rdvTwoHour" => "{$nextRdvs['1']->getDate()->format('H:i')}",
  4237.                 "rdvThreeDate" => "{$fmt->format($nextRdvs['2']->getDate())}",
  4238.                 "rdvThreeHour" => "{$nextRdvs['2']->getDate()->format('H:i')}",
  4239.                 "rdvFourDate" => "{$fmt->format($nextRdvs['3']->getDate())}",
  4240.                 "rdvFourHour" => "{$nextRdvs['3']->getDate()->format('H:i')}",
  4241.             );
  4242.     
  4243.             $publicFunction->sendEmail($params, $client->getMail(), $client->getName().' '.$client->getLastName(), "Annulation de vos prochains RDV", 162 );
  4244.         }
  4245.     foreach($nextRdvs as $rdv)
  4246.     {
  4247.         $entityManager->remove($rdv);
  4248.     }
  4249.     $entityManager->persist($client);
  4250.     $entityManager->remove($clientDevice);
  4251.     $entityManager->flush();
  4252. }*/
  4253.         $entityManager->flush();
  4254.         return new Response(json_encode(([
  4255.             "id" => $rdv->getId(),
  4256.             "motif_id" => $rdv->getIdMotif()->getId(),
  4257.             "motif_libelle" => $rdv->getIdMotif()->getTitre(),
  4258.             "audio_id" => $rdv->getIdAudio()->getId(),
  4259.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  4260.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  4261.             "fullName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  4262.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  4263.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  4264.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  4265.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  4266.             "centre_name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : null,
  4267.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  4268.             "etat_id" => $rdv->getIdEtat()->getId(),
  4269.             "date" => $rdv->getDate(),
  4270.             "comment" => $rdv->getComment(),
  4271.             "note" => $rdv->getNote(),
  4272.             "review" => $rdv->getReview(),
  4273.             "status" => 200,
  4274.         ])));
  4275.     }
  4276.     /**
  4277.      * @Route("/rdv/calendar", name="postRdvCalendar", methods={"POST"})
  4278.      */
  4279.     public function postRdvCalendar(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendarRdvSmsService $rdvSms): Response
  4280.     {
  4281.         $data json_decode($request->getContent(), true);
  4282.         if (!isset($data["token"])) {
  4283.             return new Response(json_encode([
  4284.                 "message" => "Pas de token n'a été spécifié",
  4285.                 "status" => 401,
  4286.             ]), 401);
  4287.         }
  4288.         $entityManager $this->getDoctrine()->getManager();
  4289.         /** @var Token */
  4290.         $token $this->getDoctrine()
  4291.             ->getRepository(Token::class)
  4292.             ->findOneBy(['token' => $data["token"]]);
  4293.         if (!$token) {
  4294.             return new Response(json_encode([
  4295.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  4296.                 "status" => 404,
  4297.             ]), 404);
  4298.         }
  4299.         // get token age
  4300.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  4301.         // if the token if older than 7 days
  4302.         if ($dateDiff->7) {
  4303.             $entityManager->remove($token);
  4304.             $entityManager->flush();
  4305.             return $this->json([
  4306.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  4307.                 'path' => 'src/Controller/ClientController.php',
  4308.                 "status" => 401,
  4309.             ], 401);
  4310.         }
  4311.         // makes the rdv
  4312.         $rdv = new Rdv();
  4313.         if ($token->getIdAudio()) {
  4314.             //if the token if for an audio
  4315.             $audio $token->getIdAudio();
  4316.             if ((isset($data["client_id"]))) {
  4317.                 $client $this->getDoctrine()
  4318.                     ->getRepository(Client::class)
  4319.                     ->findOneBy(['id' => $data["client_id"]]);
  4320.             } else {
  4321.                 $client $this->getDoctrine()
  4322.                     ->getRepository(ClientTemp::class)
  4323.                     ->findOneBy(['id' => $data["client_id_temp"]]);
  4324.             }
  4325.             if ($client == null) {
  4326.                 return new Response(json_encode(([
  4327.                     'message' => 'Error, no client found at this id',
  4328.                     'path' => 'src/Controller/RdvController.php',
  4329.                     "status" => 400,
  4330.                 ])), 400);
  4331.             }
  4332.         } elseif ($token->getIdClient()) {
  4333.             //if the token if for a client
  4334.             $client $token->getIdClient();
  4335.             /** @var Audio */
  4336.             $audio $this->getDoctrine()
  4337.                 ->getRepository(Audio::class)
  4338.                 ->findOneBy(['id' => $data["audio_id"]]);
  4339.             if (isset($data["proche_id"])) {
  4340.                 $proche $this->getDoctrine()
  4341.                     ->getRepository(Proches::class)
  4342.                     ->findOneBy(['id' => $data["proche_id"], "id_client" => $client]);
  4343.             }
  4344.             if ($audio == null) {
  4345.                 return new Response(json_encode(([
  4346.                     'message' => 'Error, no audio found at this id',
  4347.                     'path' => 'src/Controller/RdvController.php',
  4348.                     "status" => 400,
  4349.                 ])), 400);
  4350.             }
  4351.         } else {
  4352.             return new Response(json_encode(([
  4353.                 'message' => 'Error, token is not an audio token',
  4354.                 'path' => 'src/Controller/RdvController.php',
  4355.                 "status" => 400,
  4356.             ])), 400);
  4357.         }
  4358.         $rdv->setIdAudio($audio);
  4359.         if (isset($proche)) {
  4360.             $rdv->setIdProche($proche);
  4361.         }
  4362.         if (isset($data["client_id_temp"])) {
  4363.             $rdv->setIdClientTemp($client);
  4364.         } else {
  4365.             $rdv->setIdClient($client);
  4366.         }
  4367.         $rdv->setCacher(0);
  4368.         /** @var Centre */
  4369.         if (isset($data["centre_id"])) {
  4370.             $centre $this->getDoctrine()
  4371.                 ->getRepository(Centre::class)
  4372.                 ->findOneBy(['id' => $data["centre_id"]]);
  4373.             if ($centre == null) {
  4374.                 return new Response(json_encode(([
  4375.                     'message' => 'Error, no centre found at this id',
  4376.                     'path' => 'src/Controller/RdvController.php',
  4377.                     "status" => 400,
  4378.                 ])), 400);
  4379.             }
  4380.             /** @var AudioCentre */
  4381.             $liaison $this->getDoctrine()
  4382.                 ->getRepository(AudioCentre::class)
  4383.                 ->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
  4384.             if ($liaison == null) {
  4385.                 return new Response(json_encode(([
  4386.                     'message' => 'Error, audio isnt part of the centre',
  4387.                     'path' => 'src/Controller/RdvController.php',
  4388.                     "status" => 400,
  4389.                 ])), 400);
  4390.             }
  4391.             $rdv->setIdCentre($centre);
  4392.         } elseif (isset($data["lieu_id"]) && $audio->getIsIndie()) {
  4393.             // tries to set the lieu if it's an audio indie
  4394.             $lieu $this->getDoctrine()
  4395.                 ->getRepository(Lieu::class)
  4396.                 ->findOneBy(['id' => $data["lieu_id"], 'id_gerant' => $data["audio_id"]]);
  4397.             if ($lieu == null) {
  4398.                 return new Response(json_encode(([
  4399.                     'message' => 'Error, no lieu found at this id',
  4400.                     'path' => 'src/Controller/RdvController.php',
  4401.                     "status" => 400,
  4402.                 ])), 400);
  4403.             }
  4404.             $rdv->setIdLieu($lieu);
  4405.         } else {
  4406.             return new Response(json_encode(([
  4407.                 'message' => 'Error, no lieu/centre id',
  4408.                 'path' => 'src/Controller/RdvController.php',
  4409.                 "status" => 400,
  4410.             ])), 400);
  4411.         }
  4412.         /** @var Motif */
  4413.         $motif $this->getDoctrine()
  4414.             ->getRepository(Motif::class)
  4415.             ->find($data["motif_id"]);
  4416.         if ($motif == null) {
  4417.             return new Response(json_encode(([
  4418.                 'message' => 'Error, no motif found at this id',
  4419.                 'path' => 'src/Controller/RdvController.php',
  4420.                 "status" => 400,
  4421.             ])), 400);
  4422.         }
  4423.         /** @var AudioMotif */
  4424.         $audioMotif $this->getDoctrine()
  4425.             ->getRepository(AudioMotif::class)
  4426.             ->findOneBy(["id_audio" => $audio->getId(), "id_motif" => $data["motif_id"]]);
  4427.         if ($audioMotif == null) {
  4428.             return new Response(json_encode(([
  4429.                 'message' => 'Error, no motif of this id found at this audio',
  4430.                 'path' => 'src/Controller/RdvController.php',
  4431.                 "status" => 400,
  4432.             ])), 400);
  4433.         }
  4434.         // remove the taken schedule by rdv to make sure there is no overlap
  4435.         $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4436.         if (isset($data["note"])) {
  4437.             $rdv->setNote($data["note"]);
  4438.         }
  4439.         // test if the audio is available
  4440.         /*   if (isset($data["lieu_id"]) && $audio->getIsIndie()){
  4441.             if ($publicFunction->calculScheduleFitDate($audio, $date, $audioMotif->getDuration(), null, $lieu) == false) {
  4442.                 return new Response(json_encode(([
  4443.                     'message' => 'Error, no timestamp found at this time',
  4444.                     'path' => 'src/Controller/RdvController.php',
  4445.                     "status" => 400,
  4446.                 ])), 400);
  4447.             }
  4448.         } else {
  4449.             if ($publicFunction->calculScheduleFitDate($audio, $date, $audioMotif->getDuration(), $centre , null) == true) {
  4450.                 return new Response(json_encode(([
  4451.                     'message' => 'Error, no timestamp found at this time',
  4452.                     'path' => 'src/Controller/RdvController.php',
  4453.                     "status" => 400,
  4454.                 ])), 400);
  4455.             }
  4456.         }*/
  4457.         $rdv->setDate($date);
  4458.         $rdv->setDateCreation(\DateTime::createFromFormat("d/m/Y H:i"date('d/m/Y H:i')));
  4459.         /** @var EtatRdv */
  4460.         $etat $this->getDoctrine()
  4461.             ->getRepository(EtatRdv::class)
  4462.             ->findOneBy(['id' => $data["etat_id"]]);
  4463.         if ($etat == null) {
  4464.             return new Response(json_encode(([
  4465.                 'message' => 'Error, no etat found at this id',
  4466.                 'path' => 'src/Controller/RdvController.php',
  4467.                 "status" => 400,
  4468.             ])), 400);
  4469.         }
  4470.         $rdv->setIdEtat($etat);
  4471.         $rdv->setIdMotif($motif);
  4472.         $rdv->setDuration($data["duree"]);
  4473.         $rdv->setIsAbsence($data["is_absence"]);
  4474.         $entityManager $this->getDoctrine()->getManager();
  4475.         $entityManager->persist($rdv);
  4476.         $entityManager->flush();
  4477.         $date $rdv->getDate();
  4478.         $smsDate $date->format('d-m-Y H:i');
  4479.         $locale 'fr_FR';
  4480.         $formatter = new IntlDateFormatter(
  4481.             $locale,
  4482.             IntlDateFormatter::FULL,
  4483.             IntlDateFormatter::SHORT,
  4484.             null,
  4485.             IntlDateFormatter::GREGORIAN,
  4486.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  4487.         );
  4488.         $smsDateLongFormat $formatter->format($date);
  4489.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  4490.         // client notif mail Sms
  4491.         // we send parametre for the trait methid
  4492.         //$params = $this->emailNotificationService->prepareEmailParams($user);
  4493.         // send email notifcation
  4494.         //$this->emailNotificationService->sendEmail($params, 'admin@example.com', 'Nouvelle inscription à My Audio Pro', 1);
  4495.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  4496.         $frenchDate ucfirst($frenchDate);
  4497.         $params = array(
  4498.             "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  4499.             "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  4500.             "date" => $smsDateLongFormat,
  4501.             "prenom" => $client->getName(),
  4502.             //"heure" => $smsDatee,
  4503.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  4504.             "centerName" => $rdv->getIdCentre()->getName(),
  4505.             "centerAddress" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  4506.             "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  4507.             "centerCity" => $rdv->getIdCentre()->getCity(),
  4508.             "motif" => $rdv->getIdMotif()->getTitre(),
  4509.             "RdvDate" => substr($smsDate010) . " à "  substr($smsDate1115),
  4510.             "audioName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  4511.             "clientMail" => $client->getMail(),
  4512.             "clientPhone" => $client->getPhone(),
  4513.             'titre' => "Votre rendez-vous est validé le " substr($smsDate010) . " à "  substr($smsDate1115),
  4514.             "address" => $rdv->getIdCentre()->getAddress(),
  4515.             "postal" => $rdv->getIdCentre()->getPostale(),
  4516.             "city" => $rdv->getIdCentre()->getCity(),
  4517.             "clientEmail" => $client->getMail(),
  4518.             "clientPassword" => isset($data["passwordGenerated"]) ? $data["passwordGenerated"] : null,
  4519.             "clientAddress" => $client->getAddress(),
  4520.             "clientPostal" => $client->getPostal(),
  4521.             "clientCity" => $client->getCity(),
  4522.             "audioName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  4523.             "frenchDate" => $frenchDate,
  4524.             "heure" => substr($smsDate1115),
  4525.             "centerName" => $rdv->getIdCentre()->getName(),
  4526.             "audioMail" => $rdv->getIdAudio()->getMail(),
  4527.             "modifUrl" => "{$_ENV['BASE_client']}mes-rendez-vous",
  4528.         );
  4529.         $subject "Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  4530.         $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject181);
  4531.         $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.";
  4532.         // $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $client->getPhone());
  4533.         // audio Notif mail SMS
  4534.         /* $params = array(  
  4535.                         "lienModifer" =>"{$_ENV['BASE_logiciel']}rdv",
  4536.                         "lienAnnule"=> "{$_ENV['BASE_logiciel']}rdv",
  4537.                         "date" => substr($smsDate, 0, 10),
  4538.                         "heure" =>substr($smsDate, 11, 15),
  4539.                         'motif' => $rdv->getIdMotif()->getTitre(),
  4540.                         'clientPhone'=> $client->getPhone(),
  4541.                         'clientNom' =>$client->getLastname(),
  4542.                         'clientPrenom' =>$client->getName(),
  4543.                         'clientCivilite' => $client->getCivilite(),
  4544.                         'clientPostal' => $client->getPostal(),
  4545.                         'clientMail' => $client->getMail(),
  4546.                         'centerName' => $rdv->getIdCentre()->getName(),
  4547.                         'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4548.                         'centerCity' => $rdv->getIdCentre()->getCity(),
  4549.                         'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4550.                         'idPatient' => $client->getId(),
  4551.                         'proUrl' => "{$_ENV['BASE_logiciel']}",
  4552.                         'audioproName' => $rdv->getIdAudio()->getCivilite().' '.$rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(),
  4553.                         'titre' => 'Votre rendez-vous est modifié pour le :'
  4554.                     );
  4555.         $subject = "🔀 Rendez-vous My Audio modifié du ". $frenchDate . " à " . substr($smsDate, 11, 15);
  4556.         $publicFunction->sendEmail($params, $rdv->getIdAudio()->getMail(), $rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(), $subject, 186 );
  4557.         $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.";
  4558.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $rdv->getIdAudio()->getPhone());*/
  4559.         // google calendar post
  4560.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  4561.             ->findBy(array('audio' => $audio->getId()));
  4562.         $data['rdv'] = $rdv->getId();
  4563.         $synchronisationCosium $this->getDoctrine()->getRepository(SynchronisationCosium::class)->findOneBy(["audio" => $audio->getId()]);
  4564.         $cosiumCenter $this->getDoctrine()->getRepository(CosiumCenter::class)->findOneBy(["synchronisationCosium" => $synchronisationCosium"center" => $rdv->getIdCentre()]);
  4565.         if ($cosiumCenter) {
  4566.             $this->clientCosiumService->createAgenda($synchronisationCosium$rdv$cosiumCenter);
  4567.         }
  4568.         foreach ($synchronisations as $synchronisation) {
  4569.             if (!$synchronisation->getIsDeleted()) {
  4570.                 try {
  4571.                     $googleCalendar->checkAndRefreshAccessToken($synchronisation);
  4572.                     $googleCalendar->createEvent($synchronisation$data);
  4573.                 } catch (\Exception $e) {
  4574.                     error_log('Error refreshing access token or creating event: ' $e->getMessage());
  4575.                 }
  4576.             }
  4577.         }
  4578.         // create schedule notification sms
  4579.         $rdvSms->storeRdvSmsNotifications($rdv);
  4580.         if ($rdv->getClientDevice()) {
  4581.             $nextRdv $this->getDoctrine()
  4582.                 ->getRepository(Rdv::class)
  4583.                 ->find($rdv->getClientDevice()->getRdv()->getId());
  4584.             if ($nextRdv->getIdClientTemp()) {
  4585.                 $nextRdvs $this->getDoctrine()
  4586.                     ->getRepository(Rdv::class)
  4587.                     ->findBy([
  4588.                         "id_client_temp" => $nextRdv->getIdClientTemp(),
  4589.                         "id_motif" => ['106''107''108''109']
  4590.                     ]);
  4591.             } else {
  4592.                 $nextRdvs $this->getDoctrine()
  4593.                     ->getRepository(Rdv::class)
  4594.                     ->findBy([
  4595.                         "id_client" => $nextRdv->getIdClient(),
  4596.                         "id_motif" => ['106''107''108''109']
  4597.                     ]);
  4598.             }
  4599.             $mappedNextRdvs array_map(function ($rdv) {
  4600.                 return [
  4601.                     'id' => $rdv->getId(),
  4602.                     'date' => $rdv->getDate()->format('d-m-Y'),
  4603.                     'hours' => $rdv->getDate()->format('H:i'),
  4604.                     'duration' => $rdv->getDuration(),
  4605.                     "motif_id" => $rdv->getIdMotif()->getId(),
  4606.                     "motif_titre" => $rdv->getIdMotif()->getTitre(),
  4607.                     "duration" => $rdv->getDuration(),
  4608.                 ];
  4609.             }, $nextRdvs);
  4610.         }
  4611.         return new Response(json_encode(([
  4612.             "id" => $rdv->getId(),
  4613.             "motif_id" => $rdv->getIdMotif()->getId(),
  4614.             "audio_id" => $rdv->getIdAudio()->getId(),
  4615.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  4616.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  4617.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  4618.             "centerName" => $rdv->getIdCentre()->getName(),
  4619.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  4620.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  4621.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  4622.             "duration" => $data["duree"],
  4623.             "etat_id" => $rdv->getIdEtat()->getId(),
  4624.             "date" => $rdv->getDate(),
  4625.             "clientEtatId" => $client->getClientStatus() ? $client->getClientStatus()->getId() : 0,
  4626.             "isClient" => ($client instanceof Client) ? 0,
  4627.             "device" => $rdv->getClientDevice() ? [
  4628.                 "isDevice" => true,
  4629.                 "deviceID" => $rdv->getClientDevice()->getDevice()->getId(),
  4630.                 "clientDeviceID" => $rdv->getClientDevice()->getId(),
  4631.                 "deviceModel" => $rdv->getClientDevice()->getDevice()->getModel(),
  4632.                 "settingName" => $rdv->getClientDevice()->getSettingDevice()->getName(),
  4633.                 "settingDeviceId" => $rdv->getClientDevice()->getSettingDevice()->getSlug(),
  4634.                 "settingSlug" => $rdv->getClientDevice()->getSettingDevice()->getSlug(),
  4635.                 "nextRdvs" => $mappedNextRdvs
  4636.             ] : [
  4637.                 "isDevice" => false
  4638.             ],
  4639.             "comment" => $rdv->getComment(),
  4640.             "review" => $rdv->getReview(),
  4641.             "note" => $rdv->getNote(),
  4642.             "status" => 200,
  4643.         ])));
  4644.     }
  4645.     /**
  4646.      * @Route("/rdv/absence", name="postAbsenceCalendar", methods={"POST"})
  4647.      */
  4648.     public function postAbsenceCalendar(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendar): Response
  4649.     {
  4650.         $data json_decode($request->getContent(), true);
  4651.         if (!isset($data["token"])) {
  4652.             return new Response(json_encode([
  4653.                 "message" => "Pas de token n'a été spécifié",
  4654.                 "status" => 401,
  4655.             ]), 401);
  4656.         }
  4657.         $entityManager $this->getDoctrine()->getManager();
  4658.         /** @var Token */
  4659.         $token $this->getDoctrine()
  4660.             ->getRepository(Token::class)
  4661.             ->findOneBy(['token' => $data["token"]]);
  4662.         if (!$token) {
  4663.             return new Response(json_encode([
  4664.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  4665.                 "status" => 404,
  4666.             ]), 404);
  4667.         }
  4668.         // get token age
  4669.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  4670.         // if the token if older than 7 days
  4671.         if ($dateDiff->7) {
  4672.             $entityManager->remove($token);
  4673.             $entityManager->flush();
  4674.             return $this->json([
  4675.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  4676.                 'path' => 'src/Controller/ClientController.php',
  4677.                 "status" => 401,
  4678.             ], 401);
  4679.         }
  4680.         // makes the rdv
  4681.         $rdv = new Rdv();
  4682.         $audio $token->getIdAudio();
  4683.         $rdv->setIdAudio($audio);
  4684.         /** @var Centre */
  4685.         if (isset($data["centre_id"])) {
  4686.             $centre $this->getDoctrine()
  4687.                 ->getRepository(Centre::class)
  4688.                 ->findOneBy(['id' => $data["centre_id"]]);
  4689.             if ($centre == null) {
  4690.                 return new Response(json_encode(([
  4691.                     'message' => 'Error, no centre found at this id',
  4692.                     'path' => 'src/Controller/RdvController.php',
  4693.                     "status" => 400,
  4694.                 ])), 400);
  4695.             }
  4696.             /** @var AudioCentre */
  4697.             $liaison $this->getDoctrine()
  4698.                 ->getRepository(AudioCentre::class)
  4699.                 ->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
  4700.             if ($liaison == null) {
  4701.                 return new Response(json_encode(([
  4702.                     'message' => 'Error, audio isnt part of the centre',
  4703.                     'path' => 'src/Controller/RdvController.php',
  4704.                     "status" => 400,
  4705.                 ])), 400);
  4706.             }
  4707.             $rdv->setIdCentre($centre);
  4708.         } elseif (isset($data["lieu_id"]) && $audio->getIsIndie()) {
  4709.             // tries to set the lieu if it's an audio indie
  4710.             $lieu $this->getDoctrine()
  4711.                 ->getRepository(Lieu::class)
  4712.                 ->findOneBy(['id' => $data["lieu_id"], 'id_gerant' => $data["audio_id"]]);
  4713.             if ($lieu == null) {
  4714.                 return new Response(json_encode(([
  4715.                     'message' => 'Error, no lieu found at this id',
  4716.                     'path' => 'src/Controller/RdvController.php',
  4717.                     "status" => 400,
  4718.                 ])), 400);
  4719.             }
  4720.             $rdv->setIdLieu($lieu);
  4721.         } else {
  4722.             return new Response(json_encode(([
  4723.                 'message' => 'Error, no lieu/centre id',
  4724.                 'path' => 'src/Controller/RdvController.php',
  4725.                 "status" => 400,
  4726.             ])), 400);
  4727.         }
  4728.         // remove the taken schedule by rdv to make sure there is no overlap
  4729.         $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4730.         $rdv->setDate($date);
  4731.         $rdv->setDateCreation(\DateTime::createFromFormat("d/m/Y H:i"date('d/m/Y H:i')));
  4732.         /** @var EtatRdv */
  4733.         $etat $this->getDoctrine()
  4734.             ->getRepository(EtatRdv::class)
  4735.             ->findOneBy(['id' => $data["etat_id"]]);
  4736.         if ($etat == null) {
  4737.             return new Response(json_encode(([
  4738.                 'message' => 'Error, no etat found at this id',
  4739.                 'path' => 'src/Controller/RdvController.php',
  4740.                 "status" => 400,
  4741.             ])), 400);
  4742.         }
  4743.         $rdv->setIdEtat($etat);
  4744.         $rdv->setDuration($data["duree"]);
  4745.         $rdv->setIsAbsence($data["is_absence"]);
  4746.         $rdv->setMotifAbsence($data["motif"]);
  4747.         $rdv->setColor($data["color"]);
  4748.         $rdv->setNote($data["note"]);
  4749.         $rdv->setCacher(0);
  4750.         $entityManager $this->getDoctrine()->getManager();
  4751.         $entityManager->persist($rdv);
  4752.         $entityManager->flush();
  4753.         // create google calendar absence event
  4754.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  4755.             ->findBy(array('audio' => $audio->getId()));
  4756.         $data['rdv'] = $rdv->getId();
  4757.         $data['motif_absence'] = $rdv->getMotifAbsence() !== '' $rdv->getMotifAbsence() : "Absence";
  4758.         //        dd($data);
  4759.         foreach ($synchronisations as $synchronisation) {
  4760.             if (!$synchronisation->getIsDeleted()) {
  4761.                 try {
  4762.                     $googleCalendar->checkAndRefreshAccessToken($synchronisation);
  4763.                     $googleCalendar->createAbsenceEvent($synchronisation$data);
  4764.                 } catch (\Google\Service\Exception $e) {
  4765.                     if ($e->getCode() === 403 && str_contains($e->getMessage(), 'insufficientPermissions')) {
  4766.                         error_log("Skipped synchronisation ID {$synchronisation->getId()} due to insufficient permissions.");
  4767.                         continue;
  4768.                     }
  4769.                     throw $e;
  4770.                 }
  4771.             }
  4772.         }
  4773.         return new Response(json_encode(([
  4774.             "id" => $rdv->getId(),
  4775.             "audio_id" => $rdv->getIdAudio()->getId(),
  4776.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  4777.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  4778.             "duration" => $data["duree"],
  4779.             "etat_id" => $rdv->getIdEtat()->getId(),
  4780.             "date" => $rdv->getDate(),
  4781.             "status" => 200,
  4782.         ])));
  4783.     }
  4784.     /**
  4785.      * @Route("/rdv/{id}/absence", name="puttAbsenceCalendar", methods={"PUT"})
  4786.      */
  4787.     public function putAbsenceCalendar(Request $requestRdv $rdvPublicFunction $publicFunctionGoogleCalendarService $googleCalendar): Response
  4788.     {
  4789.         $data json_decode($request->getContent(), true);
  4790.         if (!isset($data["token"])) {
  4791.             return new Response(json_encode([
  4792.                 "message" => "Pas de token n'a été spécifié",
  4793.                 "status" => 401,
  4794.             ]), 401);
  4795.         }
  4796.         $entityManager $this->getDoctrine()->getManager();
  4797.         /** @var Token */
  4798.         $token $this->getDoctrine()
  4799.             ->getRepository(Token::class)
  4800.             ->findOneBy(['token' => $data["token"]]);
  4801.         if (!$token) {
  4802.             return new Response(json_encode([
  4803.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  4804.                 "status" => 404,
  4805.             ]), 404);
  4806.         }
  4807.         // get token age
  4808.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  4809.         // if the token if older than 7 days
  4810.         if ($dateDiff->7) {
  4811.             $entityManager->remove($token);
  4812.             $entityManager->flush();
  4813.             return $this->json([
  4814.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  4815.                 'path' => 'src/Controller/ClientController.php',
  4816.                 "status" => 401,
  4817.             ], 401);
  4818.         }
  4819.         // remove the taken schedule by rdv to make sure there is no overlap
  4820.         if (isset($data["date"])) {
  4821.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4822.             $rdv->setDate($date);
  4823.         }
  4824.         if (isset($data["duree"])) {
  4825.             $rdv->setDuration($data["duree"]);
  4826.         }
  4827.         if (isset($data["motif"])) {
  4828.             $rdv->setMotifAbsence($data["motif"]);
  4829.         }
  4830.         if (isset($data["color"])) {
  4831.             $rdv->setColor($data["color"]);
  4832.         }
  4833.         if (isset($data["note"])) {
  4834.             $rdv->setNote($data["note"]);
  4835.         }
  4836.         $entityManager $this->getDoctrine()->getManager();
  4837.         $entityManager->flush();
  4838.         $data['rdv'] = $rdv->getId();
  4839.         $data['motif_absence'] = $rdv->getMotifAbsence() !== '' $rdv->getMotifAbsence() : "Absence";
  4840.         $data['note'] = $rdv->getNote();
  4841.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  4842.             ->findBy(array('rdv' => $rdv));
  4843.         foreach ($rdvEvents as $rdvEvent) {
  4844.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  4845.             $googleCalendar->updateAbsenceEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
  4846.         }
  4847.         return new Response(json_encode(([
  4848.             "id" => $rdv->getId(),
  4849.             "audio_id" => $rdv->getIdAudio()->getId(),
  4850.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  4851.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  4852.             "duration" => $rdv->getDuration(),
  4853.             "etat_id" => $rdv->getIdEtat()->getId(),
  4854.             "date" => $rdv->getDate(),
  4855.             "status" => 200,
  4856.         ])));
  4857.     }
  4858.     /**
  4859.      * @Route("/rdv/{id}/calendar", name="editRdvCalendarByID", methods={"PUT"})
  4860.      */
  4861.     public function editRdvCalendarByID(SmsHandler $smsHandlerRdv $rdvRequest $requestGoogleCalendarService $googleCalendarPublicFunction $publicFunctionRdvSmsService $rdvSms): Response
  4862.     {
  4863.         $pastDate $rdv->getDate();
  4864.         $data json_decode($request->getContent(), true);
  4865.         $entityManager $this->getDoctrine()->getManager();
  4866.         if (!isset($data["token"])) {
  4867.             return new Response(json_encode([
  4868.                 "message" => "Pas de token n'a été spécifié",
  4869.                 "status" => 401,
  4870.             ]), 401);
  4871.         }
  4872.         /** @var Token */
  4873.         $token $this->getDoctrine()
  4874.             ->getRepository(Token::class)
  4875.             ->findOneBy(['token' => $data["token"]]);
  4876.         if (!$token) {
  4877.             return new Response(json_encode([
  4878.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  4879.                 "status" => 404,
  4880.             ]), 404);
  4881.         }
  4882.         // get token age
  4883.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  4884.         // if the token if older than 7 days
  4885.         if ($dateDiff->7) {
  4886.             $entityManager->remove($token);
  4887.             $entityManager->flush();
  4888.             return $this->json([
  4889.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  4890.                 'path' => 'src/Controller/ClientController.php',
  4891.                 "status" => 401,
  4892.             ], 401);
  4893.         }
  4894.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  4895.             return new Response(json_encode([
  4896.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  4897.                 "status" => 404,
  4898.             ]), 404);
  4899.         }
  4900.         if (isset($data["etat_id"])) {
  4901.             $etat $this->getDoctrine()
  4902.                 ->getRepository(EtatRdv::class)
  4903.                 ->findOneBy(['id' => $data["etat_id"]]);
  4904.             if ($etat == null) {
  4905.                 return new Response(json_encode(([
  4906.                     'message' => 'Error, no etat found at this id',
  4907.                     'path' => 'src/Controller/TrustedUserController.php',
  4908.                     "status" => 400,
  4909.                 ])), 400);
  4910.             }
  4911.             $rdv->setIdEtat($etat);
  4912.         }
  4913.         if (isset($data["audio_id"])) {
  4914.             $audio $this->getDoctrine()
  4915.                 ->getRepository(Audio::class)
  4916.                 ->findOneBy(['id' => $data["audio_id"]]);
  4917.             if ($audio == null) {
  4918.                 return new Response(json_encode(([
  4919.                     'message' => 'Error, no audio found at this id',
  4920.                     'path' => 'src/Controller/TrustedUserController.php',
  4921.                     "status" => 400,
  4922.                 ])), 400);
  4923.             }
  4924.             $rdv->setIdAudio($audio);
  4925.         }
  4926.         if (isset($data["motif_id"])) {
  4927.             $motif $this->getDoctrine()
  4928.                 ->getRepository(Motif::class)
  4929.                 ->find($data["motif_id"]);
  4930.             if ($motif == null) {
  4931.                 return new Response(json_encode(([
  4932.                     'message' => 'Error, no motif found at this id',
  4933.                     'path' => 'src/Controller/TrustedUserController.php',
  4934.                     "status" => 400,
  4935.                 ])), 400);
  4936.             }
  4937.             $rdv->setIdMotif($motif);
  4938.         }
  4939.         if (isset($data["client_id"])) {
  4940.             $client $this->getDoctrine()
  4941.                 ->getRepository(Client::class)
  4942.                 ->findOneBy(['id' => $data["client_id"]]);
  4943.             if ($client == null) {
  4944.                 return new Response(json_encode(([
  4945.                     'message' => 'Error, no client found at this id',
  4946.                     'path' => 'src/Controller/TrustedUserController.php',
  4947.                     "status" => 400,
  4948.                 ])), 400);
  4949.             }
  4950.             $rdv->setIdClient($client);
  4951.         }
  4952.         if (isset($data["date"])) {
  4953.             // remove the taken schedule by rdv to make sure there is no overlap
  4954.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4955.             $audioMotif $this->getDoctrine()
  4956.                 ->getRepository(AudioMotif::class)
  4957.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  4958.             if ($audioMotif == null) {
  4959.                 return new Response(json_encode(([
  4960.                     'message' => 'Error, no motif of this id found at this audio',
  4961.                     'path' => 'src/Controller/RdvController.php',
  4962.                     "status" => 400,
  4963.                 ])), 400);
  4964.             }
  4965.             if ($rdv->getIdAudio()->getIsIndie()) {
  4966.                 if ($rdv->getIdCentre()) {
  4967.                     // regular centre audio indie
  4968.                     /** @var AudioCentre */
  4969.                     $liaison $this->getDoctrine()
  4970.                         ->getRepository(AudioCentre::class)
  4971.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  4972.                     if ($liaison == null) {
  4973.                         return new Response(json_encode(([
  4974.                             'message' => 'Error, audio isnt part of the centre',
  4975.                             'path' => 'src/Controller/RdvController.php',
  4976.                             "status" => 400,
  4977.                         ])), 400);
  4978.                     }
  4979.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  4980.                         return new Response(json_encode(([
  4981.                             'message' => 'Error, no horaire found for this audio',
  4982.                             'path' => 'src/Controller/RdvController.php',
  4983.                             "status" => 400,
  4984.                         ])), 400);
  4985.                     }
  4986.                 } else {
  4987.                     // lieu audio indie
  4988.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  4989.                         return new Response(json_encode(([
  4990.                             'message' => 'Error, no horaire found for this audio',
  4991.                             'path' => 'src/Controller/RdvController.php',
  4992.                             "status" => 400,
  4993.                         ])), 400);
  4994.                     }
  4995.                 }
  4996.             } else {
  4997.                 // regular centre
  4998.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  4999.                     return new Response(json_encode(([
  5000.                         'message' => 'Error, no horaire found for this audio',
  5001.                         'path' => 'src/Controller/RdvController.php',
  5002.                         "status" => 400,
  5003.                     ])), 400);
  5004.                 }
  5005.             }
  5006.             $rdv->setDate($date);
  5007.         }
  5008.         if (isset($data["comment"]) && $token->getIdClient()) {
  5009.             $rdv->setComment($data["comment"]);
  5010.         }
  5011.         if (isset($data["review"]) && $token->getIdClient()) {
  5012.             $rdv->setReview($data["review"]);
  5013.         }
  5014.         if (isset($data["note"])) {
  5015.             $rdv->setNote($data["note"]);
  5016.         }
  5017.         $entityManager->flush();
  5018.         $date $rdv->getDate();
  5019.         $smsDate $date->format('d-m-Y H:i');
  5020.         $oldDate $pastDate->format('d-m-Y H:i');
  5021.         $locale 'fr_FR';
  5022.         $formatter = new IntlDateFormatter(
  5023.             $locale,
  5024.             IntlDateFormatter::FULL,
  5025.             IntlDateFormatter::SHORT,
  5026.             null,
  5027.             IntlDateFormatter::GREGORIAN,
  5028.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  5029.         );
  5030.         $smsDateLongFormat $formatter->format($date);
  5031.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  5032.         $frenchDate ucfirst($frenchDate);
  5033.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  5034.         // notif client
  5035.         if ($rdv->getIdEtat()->getId() != 2) {
  5036.             $params = array(
  5037.                 "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  5038.                 "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  5039.                 "date" => $smsDateLongFormat,
  5040.                 "heure" => substr($smsDate1115),
  5041.                 "motif" => $rdv->getIdMotif()->getTitre(),
  5042.                 "centerName" => $rdv->getIdCentre()->getName(),
  5043.                 "centerAddress" => $rdv->getIdCentre()->getAddress(),
  5044.                 "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  5045.                 "audioMail" => $rdv->getIdAudio()->getMail(),
  5046.                 "centerPhone" => $rdv->getIdCentre()->getPhone(),
  5047.                 "centerCity" => $rdv->getIdCentre()->getCity(),
  5048.                 "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  5049.                 'titre' => 'Votre rendez-vous est modifié pour le',
  5050.                 'frenchDate' => $frenchDate,
  5051.             );
  5052.             $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  5053.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject184);
  5054.             if ($data["sms"]) {
  5055.                 $sms "Votre RDV est modifié pour le " substr($smsDate010) . " à " substr($smsDate1115) . ", en cas d'imprévu contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
  5056.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  5057.             }
  5058.         }
  5059.         //     //// == suppression
  5060.         else if ($rdv->getIdEtat()->getId() == 2) {
  5061.             $params = array(
  5062.                 "date" => substr($smsDate010),
  5063.                 "lien" => "{$_ENV['BASE_client']}search",
  5064.                 "heure" => substr($smsDate1115),
  5065.                 "patientName" => $client->getLastName(),
  5066.                 'titre' => 'Votre rendez-vous est annulé :',
  5067.                 'centerName' => $rdv->getIdCentre()->getName(),
  5068.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  5069.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  5070.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  5071.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  5072.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  5073.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  5074.                 'motif' => $rdv->getIdMotif()->getTitre(),
  5075.             );
  5076.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  5077.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject188);
  5078.             if ($data["sms"]) {
  5079.                 $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  5080.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  5081.             }
  5082.         }
  5083.         //notif Audio
  5084.         if ($rdv->getIdEtat()->getId() != 2) {
  5085.             if ($data["sms"]) {
  5086.                 $params = array(
  5087.                     "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  5088.                     "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  5089.                     "date" => substr($smsDate010),
  5090.                     "frenchDate" => $frenchDate,
  5091.                     "heure" => substr($smsDate1115),
  5092.                     'motif' => $rdv->getIdMotif()->getTitre(),
  5093.                     'clientPhone' => $client->getPhone(),
  5094.                     'clientNom' => $client->getLastname(),
  5095.                     'clientPrenom' => $client->getName(),
  5096.                     'clientCivilite' => $client->getCivilite(),
  5097.                     'clientPostal' => $client->getPostal(),
  5098.                     'clientMail' => $client->getMail(),
  5099.                     'centerName' => $rdv->getIdCentre()->getName(),
  5100.                     'centerPostal' => $rdv->getIdCentre()->getPostale(),
  5101.                     'centerCity' => $rdv->getIdCentre()->getCity(),
  5102.                     'centerAddress' => $rdv->getIdCentre()->getAddress(),
  5103.                     'idPatient' => $client->getId(),
  5104.                     'proUrl' => "{$_ENV['BASE_logiciel']}",
  5105.                     'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  5106.                     'titre' => 'Votre rendez-vous est modifié pour le :'
  5107.                 );
  5108.                 $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  5109.                 $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  5110.                 if ($rdv->getIdAudio()->getModifRdvMail()) {
  5111.                     $subject "🔀 Rendez-vous My Audio modifié du " $frenchDate " à " substr($smsDate1115);
  5112.                     $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject186);
  5113.                 }
  5114.                 if ($rdv->getIdAudio()->getModifRdvSms()) {
  5115.                     $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.";
  5116.                     // $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $phoneAudio);
  5117.                 }
  5118.             }
  5119.         } else if ($rdv->getIdEtat()->getId() == 2) {
  5120.             if ($data["sms"]) {
  5121.                 $params = array(
  5122.                     "date" => substr($smsDate010),
  5123.                     "lien" => "{$_ENV['BASE_client']}search",
  5124.                     "heure" => substr($smsDate1115),
  5125.                     "patientName" => $client->getLastName(),
  5126.                     'titre' => 'Votre rendez-vous est annulé :',
  5127.                     'centerName' => $rdv->getIdCentre()->getName(),
  5128.                     'centerPostal' => $rdv->getIdCentre()->getPostale(),
  5129.                     'centerCity' => $rdv->getIdCentre()->getCity(),
  5130.                     'centerAddress' => $rdv->getIdCentre()->getAddress(),
  5131.                     'centerPhone' => $rdv->getIdCentre()->getPhone(),
  5132.                     'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  5133.                     'audioMail' => $rdv->getIdAudio()->getMail(),
  5134.                     'motif' => $rdv->getIdMotif()->getTitre(),
  5135.                 );
  5136.                 $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  5137.                 $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  5138.                 if ($rdv->getIdAudio()->getModifRdvMail()) {
  5139.                     $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  5140.                     $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject188);
  5141.                 }
  5142.                 if ($rdv->getIdAudio()->getModifRdvSms()) {
  5143.                     $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.";
  5144.                     //$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $phoneAudio);
  5145.                 }
  5146.             }
  5147.         }
  5148.         /* generate sms notif on update */
  5149.         // update sms notification     
  5150.         $rdvSms->updateRdvSms($rdv);
  5151.         // google calendar update
  5152.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  5153.             ->findBy(array('audio' => $rdv->getIdAudio()));
  5154.         $data['rdv'] = $rdv->getId();
  5155.         $data['motif_id'] = $rdv->getIdMotif();
  5156.         $data['note'] = $rdv->getNote();
  5157.         if ($rdv->getIdClient() !== null) {
  5158.             $data["client_id"] = $rdv->getIdClient()->getId();
  5159.         }
  5160.         if ($rdv->getIdClientTemp() !== null) {
  5161.             $data["client_id_temp"] = $rdv->getIdClientTemp()->getId();
  5162.         }
  5163.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  5164.             ->findBy(array('rdv' => $rdv));
  5165.         foreach ($rdvEvents as $rdvEvent) {
  5166.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  5167.             $googleCalendar->updateEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
  5168.         }
  5169.         return new Response(json_encode(([
  5170.             "id" => $rdv->getId(),
  5171.             "motif_id" => $rdv->getIdMotif()->getId(),
  5172.             "audio_id" => $rdv->getIdAudio()->getId(),
  5173.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  5174.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  5175.             "fullName" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  5176.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  5177.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  5178.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  5179.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  5180.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  5181.             "centre_id" => $rdv->getIdCentre()->getId(),
  5182.             "centerName" => $rdv->getIdCentre()->getName(),
  5183.             "etat_id" => $rdv->getIdEtat()->getId(),
  5184.             "date" => $rdv->getDate(),
  5185.             "comment" => $rdv->getComment(),
  5186.             "note" => $rdv->getNote(),
  5187.             "review" => $rdv->getReview(),
  5188.             "status" => 200,
  5189.         ])));
  5190.     }
  5191.     /**
  5192.      * @Route("/rdv/{id}/absence", name="deletetAbsenceCalendar", methods={"DELETE"})
  5193.      */
  5194.     public function deletetAbsenceCalendar(Request $requestRdv $rdvGoogleCalendarService $googleCalendar): Response
  5195.     {
  5196.         $data json_decode($request->getContent(), true);
  5197.         if (!isset($data["token"])) {
  5198.             return new Response(json_encode([
  5199.                 "message" => "Pas de token n'a été spécifié",
  5200.                 "status" => 401,
  5201.             ]), 401);
  5202.         }
  5203.         $entityManager $this->getDoctrine()->getManager();
  5204.         /** @var Token */
  5205.         $token $this->getDoctrine()
  5206.             ->getRepository(Token::class)
  5207.             ->findOneBy(['token' => $data["token"]]);
  5208.         if (!$token) {
  5209.             return new Response(json_encode([
  5210.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  5211.                 "status" => 404,
  5212.             ]), 404);
  5213.         }
  5214.         // get token age
  5215.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  5216.         // if the token if older than 7 days
  5217.         if ($dateDiff->7) {
  5218.             $entityManager->remove($token);
  5219.             $entityManager->flush();
  5220.             return $this->json([
  5221.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  5222.                 'path' => 'src/Controller/ClientController.php',
  5223.                 "status" => 401,
  5224.             ], 401);
  5225.         }
  5226.         // delete google agenda event
  5227.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  5228.             ->findBy(array('rdv' => $rdv));
  5229.         //dd($rdvEvents);
  5230.         foreach ($rdvEvents as $rdvEvent) {
  5231.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  5232.             $googleCalendar->deleteEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId());
  5233.             $entityManager->remove($rdvEvent);
  5234.             $entityManager->flush();
  5235.         }
  5236.         $entityManager->remove($rdv);
  5237.         $entityManager->flush();
  5238.         return new Response(json_encode(([
  5239.             "message" => "Absence Supprime",
  5240.             "status" => 200,
  5241.         ])));
  5242.     }
  5243.     /**
  5244.      * @Route("/rdvs/facturation/rdv", name="getMyRDV", methods={"GET"})
  5245.      */
  5246.     public function getMyRDV(Request $request): Response
  5247.     {
  5248.         /* $date = new DateTime();
  5249.         $minutes_to_add = 10;
  5250.         $date->add(new DateInterval('PT' . $minutes_to_add . 'M'));
  5251.         $date->setTimezone(new DateTimeZone('Europe/Paris'));
  5252.         $currentDate = $date->format('Y-m-d H:i:00');
  5253.         $toSend = $this->getDoctrine()->getRepository(Rdv::class)
  5254.             ->findRdvsIn10Mins($currentDate); 
  5255.         */
  5256.     }
  5257.     /**
  5258.      * @Route("/rdvs/facturation/lead", name="getMyLead", methods={"GET"})
  5259.      */
  5260.     public function getMyLead(Request $request): Response {}
  5261.     /**
  5262.      * @Route("/rdvs/total-count", name="getRdvCount", methods={"GET"})
  5263.      */
  5264.     public function getRdvCount(Request $request): Response
  5265.     {
  5266.         $rdvs $this->getDoctrine()->getRepository(Rdv::class)->findAll();
  5267.         return new Response(count($rdvs));
  5268.     }
  5269.     /**
  5270.      * @Route("/admin/update-relance/{id}", name="admin_update_relance", methods={"POST"})
  5271.      */
  5272.     public function updateRelance(Request $requestLeadRdv $leadEntityManagerInterface $em): JsonResponse
  5273.     {
  5274.         $data json_decode($request->getContent(), true);
  5275.         $relanceCount $data['relanceCount'] ?? null;
  5276.         if ($relanceCount !== null) {
  5277.             $lead->setRelanceCallCount((int)$relanceCount);
  5278.             $em->flush();
  5279.             return new JsonResponse(['success' => true]);
  5280.         }
  5281.         return new JsonResponse(['success' => false], 400);
  5282.     }
  5283.     /**
  5284.      * @Route("/rdv/lead", name="postLeadRdv", methods={"POST"})
  5285.      */
  5286.     public function postLeadRdv(Request $requestEntityManagerInterface $entityManagerPublicFunction $publicFunctionGoogleCalendarService $googleCalendar): Response
  5287.     {
  5288.         $data json_decode($request->getContent(), true);
  5289.         $today = new DateTime();
  5290.         try {
  5291.             $client null;
  5292.             // Gestion du client via token ou création
  5293.             if (!empty($data['clientToken'])) {
  5294.                 $token $entityManager->getRepository(Token::class)->findOneBy(['token' => $data['clientToken']]);
  5295.                 $client $token $token->getIdClient() : null;
  5296.             } elseif (!empty($data['client'])) {
  5297.                 $clientData $this->createOrGetClient($data['client']);
  5298.                 $client $entityManager->getRepository(Client::class)->find($clientData['id']);
  5299.             }
  5300.             if (!$client) {
  5301.                 return $this->json(["status" => 400"message" => "Client non trouvé ou invalide"], 400);
  5302.             }
  5303.             // Création du rendez-vous LeadRdv
  5304.             $rdvLead = new LeadRdv();
  5305.             $rdvLead->setClient($client);
  5306.             if (isset($data['titleLead'])) {
  5307.                 $rdvLead->setTitleLead($data['titleLead']);
  5308.             }
  5309.             if (isset($data['rangeAge'])) {
  5310.                 $rdvLead->setRangeAge($data['rangeAge']);
  5311.             }
  5312.             if (isset($data['situations'])) {
  5313.                 $rdvLead->setSituationsGene($data['situations']);
  5314.             }
  5315.             if (isset($data['equipe'])) {
  5316.                 $rdvLead->setEquipeAppareil($data['equipe']);
  5317.             }
  5318.             if (isset($data['durationEquipe'])) {
  5319.                 $rdvLead->setDurationEquipeAppareil($data['durationEquipe']);
  5320.             }
  5321.             if (isset($data['bilanAuditif'])) {
  5322.                 $rdvLead->setBilanAuditif($data['bilanAuditif']);
  5323.             }
  5324.             if (isset($data['ordonance'])) {
  5325.                 $rdvLead->setOrdonance($data['ordonance']);
  5326.             }
  5327.             if (isset($data['dateOrdonance'])) {
  5328.                 $rdvLead->setDateOrdonance($data['dateOrdonance']);
  5329.             }
  5330.             if (isset($data['canMove'])) {
  5331.                 $rdvLead->setCanMove($data['canMove']);
  5332.             }
  5333.             if (isset($data['traffic_source'])) {
  5334.                 $rdvLead->setTrafficSource($data['traffic_source']);
  5335.             }
  5336.             if (isset($data['article_name'])) {
  5337.                 $rdvLead->setTrafficLpVersion($data['article_name']);
  5338.             }
  5339.             if (isset($data['lp_version'])) {
  5340.                 $rdvLead->setTrafficArticleName($data['lp_version']);
  5341.             }
  5342.             if (isset($data['isNewLp'])) {
  5343.                 $rdvLead->setIsNewLp($data['isNewLp']);
  5344.                 $leadStatus $entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'demande_contact']);
  5345.                 if ($leadStatus) {
  5346.                     $rdvLead->setLeadStatus($leadStatus);
  5347.                 }
  5348.             }
  5349.             $rdvLead->setDate($today);
  5350.             if (!empty($data['audio'])) {
  5351.                 $audio $entityManager->getRepository(Audio::class)->find($data['audio']);
  5352.                 if ($audio) {
  5353.                     $rdvLead->setAudio($audio);
  5354.                 }
  5355.             }
  5356.             if ($client->getPostal()) {
  5357.                 $centerCount $this->getMatchingCentresCount($client->getPostal());
  5358.                 $rdvLead->setCentersCount($centerCount);
  5359.                 if ($centerCount == 0) {
  5360.                     $leadStatus $entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'hors_zone']);
  5361.                     if ($leadStatus) {
  5362.                         $rdvLead->setLeadStatus($leadStatus);
  5363.                     }
  5364.                 }
  5365.             }
  5366.             // Création du Token
  5367.             $tokenString $publicFunction->generateRandomString(30);
  5368.             $token = (new Token())
  5369.                 ->setCreationDate(new DateTime())
  5370.                 ->setToken($tokenString)
  5371.                 ->setIdClient($client);
  5372.             $entityManager->persist($rdvLead);
  5373.             $entityManager->persist($token);
  5374.             $entityManager->flush();
  5375.             return $this->json([
  5376.                 "id" => $client->getId(),
  5377.                 "idRdvLead" => $rdvLead->getId(),
  5378.                 "name" => $client->getName(),
  5379.                 "lastname" => $client->getLastname(),
  5380.                 "token" => $tokenString,
  5381.                 "code" => $clientData['password'],
  5382.                 "postalCode" => $client->getPostal() ?? null,
  5383.                 "status" => 200,
  5384.             ]);
  5385.         } catch (\Exception $e) {
  5386.             return $this->json(["status" => 500"message" => $e->getMessage()], 500);
  5387.         }
  5388.     }
  5389.     /**
  5390.      * @Route("/testGenerateVoice", name="testGenerateVoice", methods={"GET"})
  5391.      */
  5392.     public function testGenerateVoice(AppointmentCallService $service): Response
  5393.     {
  5394.         // TEST LOCAL$rdv = $this->entityManager->getRepository(Rdv::class)->find(6653);
  5395.         $rdv $this->entityManager->getRepository(Rdv::class)->find(2306);
  5396.         $lead $this->entityManager->getRepository(LeadRdv::class)->find(496);
  5397.         // $service->handleCallCenterAfterRdv(
  5398.         //     $rdv
  5399.         // );
  5400.         // $service->handleReminderCallToPatient(
  5401.         //     $rdv
  5402.         // );
  5403.         $service->handleEquipmentStatusCall($rdv);
  5404.         // $service->handleReminderCallToPatientOneHourBefore(
  5405.         //     $rdv
  5406.         // );
  5407.         // $service->handleCallToPatientAfterRdv(
  5408.         //     $rdv
  5409.         // );
  5410.         // $service->handleFollowupCall15Days($rdv);
  5411.         // $service->handleNewLeadCall($lead, "+33743393532");
  5412.         // $service->handleFollowupCall31Days($rdv);
  5413.         return new Response(json_encode([
  5414.             "status" => 200,
  5415.         ]), 200, ['Content-Type' => 'application/json']);
  5416.     }
  5417.     /**
  5418.      * @Route("/testSynthflow", name="testSynthflow", methods={"POST"})
  5419.      */
  5420.     public function testSynthflow(SynthflowService $service): Response
  5421.     {
  5422.         // TEST LOCAL
  5423.         $lead $this->entityManager->getRepository(LeadRdv::class)->find(496);
  5424.         $service->initiateCall($lead);
  5425.         return new Response(json_encode([
  5426.             "status" => 200,
  5427.         ]), 200, ['Content-Type' => 'application/json']);
  5428.     }
  5429.     /**
  5430.      * Private method to create a new client or get existing one by phone
  5431.      */
  5432.     private function createOrGetClient(array $data): array
  5433.     {
  5434.         $clientRepository $this->entityManager->getRepository(Client::class);
  5435.         // check sur le mail et phone
  5436.         $existingClient $clientRepository->findOneBy(['mail' => $data['email']]);
  5437.         if ($existingClient) {
  5438.             if ($existingClient->getPostal() !== $data['postalCode']) {
  5439.                 $existingClient->setPostal($data['postalCode']);
  5440.                 $this->entityManager->persist($existingClient);
  5441.                 $this->entityManager->flush();
  5442.             }
  5443.             return ['id' => $existingClient->getId(), 'password' => 'Votre mot de passe'];
  5444.         }
  5445.         $randomPassword $this->generateRandomPassword(12);
  5446.         $client = new Client();
  5447.         $client->setLastname($data['lastname']);
  5448.         $client->setBirthdate(null);
  5449.         $client->setName($data['firstname']);
  5450.         $client->setPhone($data['phone']);
  5451.         $client->setMail($data['email']);
  5452.         $client->setSignupDate(new \DateTime());
  5453.         $client->setPassword(password_hash($randomPasswordPASSWORD_DEFAULT));
  5454.         $client->setPostal($data['postalCode']);
  5455.         $client->setAddress($data['address'] ?? null);
  5456.         $client->setCity($data['city'] ?? null);
  5457.         $client->setDesactivate(false);
  5458.         if (isset($data['civilite'])) {
  5459.             $civilite = ($data['civilite'] === 'Homme') ? 'Monsieur' 'Madame';
  5460.             $client->setCivilite($civilite);
  5461.         }
  5462.         $this->entityManager->persist($client);
  5463.         $this->entityManager->flush();
  5464.         return ['id' => $client->getId(), 'password' => $randomPassword];
  5465.     }
  5466.     private function generateRandomPassword($length 10): string
  5467.     {
  5468.         return bin2hex(random_bytes($length 2));
  5469.     }
  5470.     private function getMatchingCentresCount($clientPostal): int
  5471.     {
  5472.         // Récupérer les coordonnées GPS du code postal du client
  5473.         $clientCoordinates $this->entityManager
  5474.             ->getRepository(RegionDepartment::class)
  5475.             ->findOneBy(['codePostal' => $clientPostal]);
  5476.         $clientLat $clientCoordinates $clientCoordinates->getLatitude() : null;
  5477.         $clientLon $clientCoordinates $clientCoordinates->getLongitude() : null;
  5478.         $centres $this->entityManager->getRepository(Centre::class)->findAll();
  5479.         $count 0;
  5480.         foreach ($centres as $centre) {
  5481.             if ($centre->getZoneKm()) {
  5482.                 $latitude $centre->getLatitude();
  5483.                 $longitude $centre->getLongitude();
  5484.                 $radius $centre->getZoneKm();
  5485.                 $postals $this->entityManager->getRepository(RegionDepartment::class)->findPostalsWithinRadius($latitude$longitude$radius);
  5486.                 $postalCodes array_values(array_unique(array_column($postals'code_postal')));
  5487.                 if (in_array($clientPostal$postalCodes)) {
  5488.                     $count++;
  5489.                 }
  5490.             }
  5491.         }
  5492.         return $count;
  5493.     }
  5494.     /**
  5495.      * @Route("/rdv/send-map", name="getRdvMap", methods={"POST"})
  5496.      */
  5497.     public function sendEmailWithMap(Request $requestPublicFunction $publicFunction): Response
  5498.     {
  5499.         $data json_decode($request->getContent(), true);
  5500.         $mail "";
  5501.         $name "";
  5502.         $centre "";
  5503.         if (isset($data['clientToken'])) {
  5504.             $token $this->getDoctrine()->getRepository(Token::class)->findOneBy(['token' => $data['clientToken']]);
  5505.             $client $token->getIdClient();
  5506.             $mail $client->getMail();
  5507.             $name $client->getLastname() . " " $client->getName();
  5508.             $centre $this->getDoctrine()->getRepository(Centre::class)->findOneBy(['id' => $data['centre']['id']]);
  5509.         } else {
  5510.             $mail $data['email'];
  5511.             $name $data['name'];
  5512.         }
  5513.         $locale 'fr_FR';
  5514.         $dateTime DateTime::createFromFormat('d/m/Y H:i'$data['date']);
  5515.         if ($dateTime) {
  5516.             $fmt = new IntlDateFormatter($localeIntlDateFormatter::FULLIntlDateFormatter::NONE);
  5517.             $fmt->setPattern("EEEE dd MMMM");
  5518.             $formattedDate ucfirst($fmt->format($dateTime));
  5519.         } else {
  5520.             $formattedDate "Date invalide";
  5521.         }
  5522.         $params = [
  5523.             'date' => $data['date'],
  5524.             'time' => $data['time'],
  5525.             'frenchDate' => $formattedDate,
  5526.             'clientAddress' => $data['address'],
  5527.             'centerName' => $centre->getName(),
  5528.             'centerAddress' => $centre->getAddress(),
  5529.             'centerPostal' => $centre->getPostale(),
  5530.             'centerCity' => $centre->getCity(),
  5531.             'start' => $data['start'],
  5532.             'end' => $data['end'],
  5533.             'urlApi' => "{$_ENV['BASE_client']}",
  5534.         ];
  5535.         $publicFunction->sendEmail($params$mail$name"Votre Rendez-vous My Audio"198);
  5536.         return new Response(json_encode([
  5537.             "status" => 200,
  5538.             "params" => $params,
  5539.         ]), 200, ['Content-Type' => 'application/json']);
  5540.     }
  5541.     /**
  5542.      * @Route("/rdv/cantmove", name="notifCantMove", methods={"POST"})
  5543.      */
  5544.     public function notifCantMove(Request $requestPublicFunction $publicFunction): Response
  5545.     {
  5546.         $data json_decode($request->getContent(), true);
  5547.         $email "lead.myaudio@gmail.com";
  5548.         $centre "";
  5549.         $type "My Audio";
  5550.         $details "";
  5551.         $picto "❌";
  5552.         $ordo "sans ordo";
  5553.         $subject "";
  5554.         if (isset($data['ordonance'])) {
  5555.             if ($data["ordonance"] == "oui") {
  5556.                 $ordo "avec ordo";
  5557.             }
  5558.         } else {
  5559.             $ordo "";
  5560.         }
  5561.         if (isset($data['centre'])) {
  5562.             $centre $data['centre'];
  5563.             $subject $picto " Lead - demande de contact ne pouvant pas se déplacer " $data['postal'] . " " $ordo;
  5564.         } else {
  5565.             $centre "";
  5566.             $type "Hors Zone";
  5567.             $details "Pas de centre dans la zone";
  5568.             $subject $picto " Lead Hors Zone " $data['postal'] . " " $ordo " ne pouvant pas se déplacer";
  5569.         }
  5570.         $responses = [
  5571.             'rangeAge' => isset($data['rangeAge']) ? $data['rangeAge'] : null,
  5572.             'situations' => isset($data['situations']) ? $data['situations'] : null,
  5573.             'equipeAppareil' => isset($data['equipe']) ? $data['equipe'] : null,
  5574.             'durationEquipe' => isset($data['durationEquipe']) ? $data['durationEquipe'] : null,
  5575.             'bilanAuditif' => isset($data['bilanAuditif']) ? $data['bilanAuditif'] : null,
  5576.             'ordonance' => isset($data['ordonance']) ? $data['ordonance'] : null,
  5577.             'dateOrdonance' => isset($data['dateOrdonance']) ? $data['dateOrdonance'] : null,
  5578.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  5579.         ];
  5580.         $department $this->getDepartmentFromPostalCode($data['address']);
  5581.         $data['departmentCode'] = $department['departmentCode'];
  5582.         $data['departmentName'] = $department['departmentName'];
  5583.         $data['regionName'] = $department['regionName'];
  5584.         $data['city'] = $department['city'];
  5585.         $params = [
  5586.             'date' => $data['date'],
  5587.             'time' => $data['time'],
  5588.             'address' => $data['address'],
  5589.             'centre' => $centre,
  5590.             'type' => $type,
  5591.             'details' => $details,
  5592.             'responses' => $responses,
  5593.             'name' => $data['name'],
  5594.             'civilite' => $data['civilite'],
  5595.             'nom' => $data['firstname'],
  5596.             'prenom' => $data['lastname'],
  5597.             'codePostal' => $data['address'],
  5598.             'telephone' => $data['phone'],
  5599.             'email' => $data['email'],
  5600.             'departement' => $data['departmentName'],
  5601.             'ville' => $data['city'],
  5602.             'region' => $data['regionName'],
  5603.             'trangeAge' => isset($data['rangAge']) ? $data['rangAge'] : null,
  5604.             'situationVecu' => isset($data['situations']) ? implode(', '$data['situations']) : null,
  5605.             'dejaEquipe' => isset($data['equipeAppareil']) ? $data['equipeAppareil'] : null,
  5606.             'trafficSource' => isset($data['traffic_source']) ? $data['traffic_source'] : null,
  5607.             'articleName' => isset($data['article_name']) ? $data['article_name'] : null,
  5608.             'lpVersion' => isset($data['lp_version']) ? $data['lp_version'] : null,
  5609.         ];
  5610.         $publicFunction->sendEmail($params$email$data['name'], $subject208);
  5611.         return new Response(json_encode([
  5612.             "status" => 200,
  5613.         ]), 200, ['Content-Type' => 'application/json']);
  5614.     }
  5615.     /**
  5616.      * @Route("/rdv/cantmove/v2", name="notifCantMoveV2", methods={"POST"})
  5617.      */
  5618.     public function notifCantMoveV2(Request $requestPublicFunction $publicFunction): Response
  5619.     {
  5620.         $data json_decode($request->getContent(), true);
  5621.         $email "lead.myaudio@gmail.com";
  5622.         $centre "";
  5623.         $type "My Audio";
  5624.         $details "";
  5625.         $picto "❌";
  5626.         $subject "";
  5627.         $audio "";
  5628.         $subject $picto " Lead ne pouvant pas se déplacer";
  5629.         $department $this->getDepartmentFromPostalCode($data['address']);
  5630.         $data['departmentCode'] = $department['departmentCode'];
  5631.         $data['departmentName'] = $department['departmentName'];
  5632.         $data['regionName'] = $department['regionName'];
  5633.         $data['city'] = $department['city'];
  5634.         $password "";
  5635.         $params = [
  5636.             'name' => $data['name'],
  5637.             'civilite' => $data['civilite'],
  5638.             'nom' => $data['firstname'],
  5639.             'prenom' => $data['lastname'],
  5640.             'codePostal' => $data['address'],
  5641.             'telephone' => $data['phone'],
  5642.             'email' => $data['email'],
  5643.             'password' => $data['clientSecretCookie'],
  5644.             'trancheAge' => isset($data['rangAge']) ? $data['rangAge'] : null,
  5645.             'situationVecu' => isset($data['situations']) ? implode(', '$data['situations']) : null,
  5646.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  5647.             'trafficSource' => isset($data['traffic_source']) ? $data['traffic_source'] : null,
  5648.             'articleName' => isset($data['article_name']) ? $data['article_name'] : null,
  5649.             'lpVersion' => isset($data['lp_version']) ? $data['lp_version'] : null,
  5650.             'urlLogin' => "{$_ENV['BASE_client']}login"
  5651.         ];
  5652.         // Send email to MyAudio
  5653.         $publicFunction->sendEmail($params$email$data['name'], $subject220);
  5654.         $publicFunction->sendEmail($params'contact@myaudio.fr'$data['name'], $subject220);
  5655.         // Send email to patient
  5656.         $params = [
  5657.             'clientEmail' => $data['email'],
  5658.             'clientPassword' => $data['clientSecretCookie'],
  5659.             'rdv' => "https://www.myaudio.fr/search",
  5660.             'urlLogin' => "{$_ENV['BASE_client']}login"
  5661.         ];
  5662.         $publicFunction->sendEmail($params$data['email'], $data['name'], 'Rendez-vous My Audio - En cours de traitement'219);
  5663.         $rdvLead $this->entityManager->getRepository(LeadRdv::class)->find($data['clientRdvLp']);
  5664.         if ($rdvLead) {
  5665.             $leadStatus $this->entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'cant_move']);
  5666.             if ($leadStatus) {
  5667.                 $rdvLead->setLeadStatus($leadStatus);
  5668.                 $this->entityManager->flush();
  5669.             }
  5670.         }
  5671.         return new Response(json_encode([
  5672.             "status" => 200,
  5673.         ]), 200, ['Content-Type' => 'application/json']);
  5674.     }
  5675.     /**
  5676.      * @Route("/rdv/notiflead", name="notifLead", methods={"POST"})
  5677.      */
  5678.     public function notifLeadRdv(Request $requestPublicFunction $publicFunction): Response
  5679.     {
  5680.         $data json_decode($request->getContent(), true);
  5681.         $email "lead.myaudio@gmail.com";
  5682.         $centre "";
  5683.         $type "My Audio";
  5684.         $details "";
  5685.         $picto "❌";
  5686.         $ordo "sans ordo";
  5687.         $subject "";
  5688.         $name "";
  5689.         $postal "";
  5690.         $emailPatient "";
  5691.         if (isset($data['clientToken']) && !empty($data['clientToken'])) {
  5692.             $token $this->getDoctrine()->getRepository(Token::class)->findOneBy(['token' => $data['clientToken']]);
  5693.             $client $token->getIdClient();
  5694.             $name $client->getLastname() . " " $client->getName();
  5695.             $postal $client->getPostal();
  5696.             $emailPatient $client->getMail();
  5697.         } else {
  5698.             if (isset($data['postal'])) {
  5699.                 $postal $data['postal'];
  5700.             }
  5701.             if (isset($data['name'])) {
  5702.                 $name $data['name'];
  5703.             }
  5704.             if (isset($data['email'])) {
  5705.                 $email $data['email'];
  5706.             }
  5707.             if (isset($data['email'])) {
  5708.                 $emailPatient $data['email'];
  5709.             }
  5710.         }
  5711.         if (isset($data["ordonance"])) {
  5712.             if ($data["ordonance"] == "oui") {
  5713.                 $ordo "avec ordo";
  5714.             }
  5715.         }
  5716.         if (isset($data['centre'])) {
  5717.             $centre $data['centre'];
  5718.             $picto "✅";
  5719.             $subject $picto " Lead booké " $postal " " $ordo;
  5720.         } else {
  5721.             $centre "";
  5722.             $type "Hors Zone";
  5723.             $details "Pas de centre dans la zone";
  5724.             $subject $picto " Lead Hors Zone " $postal " " $ordo;
  5725.         }
  5726.         $responses = [
  5727.             'rangeAge' => isset($data['rangeAge']) ? $data['rangeAge'] : null,
  5728.             'situations' => isset($data['situations']) ? $data['situations'] : null,
  5729.             'equipeAppareil' => isset($data['equipe']) ? $data['equipe'] : null,
  5730.             'durationEquipe' => isset($data['durationEquipe']) ? $data['durationEquipe'] : null,
  5731.             'bilanAuditif' => isset($data['bilanAuditif']) ? $data['bilanAuditif'] : null,
  5732.             'ordonance' => isset($data['ordonance']) ? $data['ordonance'] : null,
  5733.             'dateOrdonance' => isset($data['dateOrdonance']) ? $data['dateOrdonance'] : null,
  5734.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  5735.         ];
  5736.         $params = [
  5737.             'date' => $data['date'],
  5738.             'time' => $data['time'],
  5739.             'address' => $data['address'],
  5740.             'centre' => $centre,
  5741.             'type' => $type,
  5742.             'details' => $details,
  5743.             'responses' => $responses,
  5744.             'name' => $name,
  5745.             'email' => $emailPatient,
  5746.         ];
  5747.         $publicFunction->sendEmail($params$email$name$subject180);
  5748.         return new Response(json_encode([
  5749.             "status" => 200,
  5750.             "params" => $params,
  5751.             "responses" => $responses
  5752.         ]), 200, ['Content-Type' => 'application/json']);
  5753.     }
  5754.     /**
  5755.      *  Met à jour l'état d'un rendez-vous.
  5756.      *
  5757.      * Cette fonction permet de modifier l'état d'un rendez-vous en fonction des données envoyées
  5758.      * via une requête PUT. Elle effectue plusieurs vérifications, notamment :
  5759.      * - La présence et la validité du token d'authentification.
  5760.      * - L'existence du rendez-vous et du nouvel état.
  5761.      * - L'expiration du token (plus de 7 jours).
  5762.      * 
  5763.      * Si le rendez-vous est marqué comme "Absence injustifiée" (état ID 3), un email et un SMS sont envoyés
  5764.      * au client et à l'équipe MyAudio pour les informer.
  5765.      * 
  5766.      * @Route("api/save-etat-rdv", name="saveEtatRdv", methods={"PUT"})
  5767.      */
  5768.     public function saveEtatRdv(Request $requestPublicFunction $publicFunction): Response
  5769.     {
  5770.         $entityManager $this->getDoctrine()->getManager();
  5771.         $data json_decode($request->getContent(), true);
  5772.         if (!$data['token']) {
  5773.             return new Response(json_encode([
  5774.                 "message" => "Pas de token n'a été spécifié",
  5775.                 "status" => 401,
  5776.             ]), 401);
  5777.         }
  5778.         /** @var Token */
  5779.         $token $this->getDoctrine()
  5780.             ->getRepository(Token::class)
  5781.             ->findOneBy(['token' => $data['token'], 'id_audio' => $data['audio']]);
  5782.         if (!$token) {
  5783.             return new Response(json_encode([
  5784.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  5785.                 "status" => 404,
  5786.             ]), 404);
  5787.         }
  5788.         // get token age
  5789.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  5790.         // if the token if older than 7 days
  5791.         if ($dateDiff->7) {
  5792.             $entityManager->remove($token);
  5793.             $entityManager->flush();
  5794.             return $this->json([
  5795.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  5796.                 'path' => 'src/Controller/ClientController.php',
  5797.                 "status" => 401,
  5798.             ], 401);
  5799.         }
  5800.         $rdv $this->getDoctrine()->getRepository(Rdv::class)->find($data['rdv']);
  5801.         if (!$rdv) {
  5802.             return new Response(json_encode([
  5803.                 "message" => "Rdv not found.",
  5804.                 "status" => 404,
  5805.             ]), 404);
  5806.         }
  5807.         $rdvEtat $this->getDoctrine()
  5808.             ->getRepository(EtatRdv::class)
  5809.             ->find($data['etat']);
  5810.         if (!$rdvEtat) {
  5811.             return new Response(json_encode([
  5812.                 "message" => "Rdv etat not found.",
  5813.                 "status" => 404,
  5814.             ]), 404);
  5815.         }
  5816.         $rdv->setIdEtat($rdvEtat);
  5817.         $entityManager->flush();
  5818.         $encodedNomDuCentre rawurlencode($rdv->getIdCentre()->getName());
  5819.         $urlApi "audioprothesiste/{$rdv->getIdCentre()->getCity()}/{$rdv->getIdCentre()->getPostale()}/{$encodedNomDuCentre}/prise-de-rdvaudioprothesiste-rapide/{$rdv->getIdCentre()->getId()}";
  5820.         if ($rdvEtat->getId() == 3) {
  5821.             // Send email to client
  5822.             $date $rdv->getDate();
  5823.             $smsDate $date->format('d-m-Y H:i');
  5824.             $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  5825.             $params = array(
  5826.                 "date" => substr($smsDate010),
  5827.                 "lien" => "{$_ENV['BASE_client']}$urlApi,
  5828.                 "heure" => substr($smsDate1115),
  5829.                 'centerName' => $rdv->getIdCentre()->getName() ?? '',
  5830.                 'centerPostal' => $rdv->getIdCentre()->getPostale() ?? '',
  5831.                 'centerCity' => $rdv->getIdCentre()->getCity() ?? '',
  5832.                 'centerAddress' => $rdv->getIdCentre()->getAddress() ?? '',
  5833.                 'centerPhone' => $rdv->getIdCentre()->getPhone() ?? '',
  5834.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName() ?? '',
  5835.                 'audioMail' => $rdv->getIdAudio()->getMail() ?? '',
  5836.             );
  5837.             $subject "Vous avez manqué votre rendez-vous MyAudio avec " $rdv->getIdCentre()->getName();
  5838.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject214);
  5839.             // Send sms to client
  5840.             $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();
  5841.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  5842.             // Send email to MyAudio
  5843.             $date $rdv->getDate();
  5844.             $smsDate $date->format('d-m-Y H:i');
  5845.             $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  5846.             $params = array(
  5847.                 "date" => substr($smsDate010),
  5848.                 "lien" => "{$_ENV['BASE_client']}search",
  5849.                 "heure" => substr($smsDate1115),
  5850.                 'centerName' => $rdv->getIdCentre()->getName() ?? '',
  5851.                 'centerPostal' => $rdv->getIdCentre()->getPostale() ?? '',
  5852.                 'centerCity' => $rdv->getIdCentre()->getCity() ?? '',
  5853.                 'centerAddress' => $rdv->getIdCentre()->getAddress() ?? '',
  5854.                 'centerPhone' => $rdv->getIdCentre()->getPhone() ?? '',
  5855.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName() ?? '',
  5856.                 'audioMail' => $rdv->getIdAudio()->getMail() ?? '',
  5857.                 'clientName' => $client->getName() . ' ' $client->getLastName() ?? '',
  5858.                 'clientMail' => $client->getMail() ?? '',
  5859.                 'clientPhone' => $client->getPhone() ?? '',
  5860.             );
  5861.             $subject "Le patient " $client->getName() . ' ' $client->getLastName() . " a manqué son rendez-vous MyAudio avec le centre " $rdv->getIdCentre()->getName();
  5862.             $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$client->getName() . ' ' $client->getLastName(), $subject215);
  5863.         }
  5864.         return new Response(json_encode([
  5865.             "message" => "rdvEtat has been successfully updated",
  5866.             "status" => 200,
  5867.         ]));
  5868.     }
  5869.     /**
  5870.      * 
  5871.      * @Route("api/send-email/clientnotcompletebook", name="askToContact", methods={"POST"})
  5872.      */
  5873.     public function askToContact(Request $requestPublicFunction $publicFunction): Response
  5874.     {
  5875.         $data json_decode($request->getContent(), true);
  5876.         $staticToken "3f3a8b74f3e5b2d0c4917f5f9a7c07efb1a0f1e5e8c907ec9c4e9df129e3125e9";
  5877.         $token $data['token'] ?? null;
  5878.         if ($token !== $staticToken) {
  5879.             return new JsonResponse(
  5880.                 [
  5881.                     'status' => 'error',
  5882.                     'code' => 'unauthorized',
  5883.                     'message' => 'Unauthorized access.'
  5884.                 ],
  5885.                 JsonResponse::HTTP_UNAUTHORIZED
  5886.             );
  5887.         }
  5888.         $params = [
  5889.             'clientCivilite' => isset($data['civilite']) ? $data['civilite'] : 'Pas indiqué',
  5890.             'clientNom' => isset($data['firstname']) ? $data['firstname'] : null,
  5891.             'clientPrenom' => isset($data['lastname']) ? $data['lastname'] : null,
  5892.             'clientPostal' => isset($data['postalCode']) ? $data['postalCode'] : null,
  5893.             'clientPhone' => isset($data['phone']) ? $data['phone'] : null,
  5894.             'clientMail' => isset($data['email']) ? $data['email'] : null,
  5895.             'password' => isset($data['clientSecretCookie']) ? $data['clientSecretCookie'] : null,
  5896.             'rangeAge' => isset($data['trancheAge']) ? $data['trancheAge'] : null,
  5897.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  5898.             'situations' => isset($data['situations']) ? implode(', '$data['situations']) : null,
  5899.             'trafficSource' => isset($data['traffic_source']) ? $data['traffic_source'] : null,
  5900.             'articleName' => isset($data['article_name']) ? $data['article_name'] : null,
  5901.             'lpVersion' => isset($data['lp_version']) ? $data['lp_version'] : null,
  5902.         ];
  5903.         $templateEmailMyAudio 223;
  5904.         if (!empty($data['centre'])) {
  5905.             $centre $data['centre'];
  5906.             $audio $centre['audio'][0];
  5907.             $params['centerName'] = $centre['name'] ?? null;
  5908.             $params['centerPostal'] = $centre['postale'] ?? null;
  5909.             $params['centerCity'] = $centre['city'] ?? null;
  5910.             $params['centerAddress'] = $centre['address'] ?? null;
  5911.             $params['centerPhone'] = $centre['phone'] ?? null;
  5912.             $params['audioproName'] = $audio['civilite'] . ' ' $audio['lastname'] . ' ' $audio['name'] ?? null;
  5913.             $templateEmailMyAudio 222;
  5914.         }
  5915.         // Email to My Audio
  5916.         $email "lead.myaudio@gmail.com";
  5917.         $subject "Demande de contact -  Nouveau Lead À Contacter Hors Zone";
  5918.         $publicFunction->sendEmail($params$email$data['name'], $subject$templateEmailMyAudio);
  5919.         $publicFunction->sendEmail($params'contact@myaudio.fr'$data['name'], $subject$templateEmailMyAudio);
  5920.         $coordinates $this->getCoordinatesFromPostalCode($data['postalCode']);
  5921.         $latitude $coordinates['latitude'];
  5922.         $longitude $coordinates['longitude'];
  5923.         $params = [
  5924.             'email' => isset($data['email']) ? $data['email'] : null,
  5925.             'password' => isset($data['clientSecretCookie']) ? $data['clientSecretCookie'] : null,
  5926.             "lienRdv" => "{$_ENV['BASE_client']}search?latitude={$latitude}&longitude={$longitude}&ville={$data['postalCode']}",
  5927.         ];
  5928.         // Email to Client
  5929.         $subject "My Audio - Confirmation de demande de contact";
  5930.         $publicFunction->sendEmail($params$data['email'], $data['name'], $subject221);
  5931.         $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";
  5932.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$data['phone']);
  5933.         if (isset($data['clientRdvLp'])) {
  5934.             $rdvLead $this->entityManager->getRepository(LeadRdv::class)->find($data['clientRdvLp']);
  5935.             if ($rdvLead) {
  5936.                 $rdvLead->setSendAskToContact(1);
  5937.                 $rdvLead->setCountAskToContact(($rdvLead->getCountAskToContact() ?? 0) + 1);
  5938.                 $this->entityManager->flush();
  5939.                 $this->sendWhatsApp($data$rdvLead);
  5940.             }
  5941.         }
  5942.         return new Response(json_encode([
  5943.             "message" => "Email ask for contact send with success",
  5944.             "status" => 200,
  5945.         ]));
  5946.     }
  5947.     private function sendWhatsApp($data$lead): void
  5948.     {
  5949.         $adminUrl $this->adminUrlGenerator
  5950.             ->setDashboard(DashboardController::class)
  5951.             ->setController(LeadRdvCrudController::class)
  5952.             ->setAction('detail')
  5953.             ->setEntityId($lead->getId())
  5954.             ->generateUrl();
  5955.         $relativeUrl parse_url($adminUrlPHP_URL_PATH) . '?' parse_url($adminUrlPHP_URL_QUERY);
  5956.         // Supprimer le slash en trop s’il y en a un au début
  5957.         $relativeUrl ltrim($relativeUrl'/');
  5958.         // 🧑‍🤝‍🧑 Tableau des destinataires
  5959.         $destinataires = [
  5960.             '33611879183'// Numéro 1
  5961.             '33667597626'// Numéro 2
  5962.             '447884128220'// Numéro 3
  5963.         ];
  5964.         foreach ($destinataires as $numero) {
  5965.             $this->whatsapp->sendTemplateMessage(
  5966.                 $numero,  // Numéro de téléphone du destinataire
  5967.                 'lead_notif_myaudio',  // Nom du template WhatsApp
  5968.                 [
  5969.                     'body' => [
  5970.                         ['parameter_name' => 'nom_client''text' => $data['firstname'] . ' ' $data['lastname']],  // {{nom_client}}
  5971.                         ['parameter_name' => 'email_client''text' => $data['email'] ?? ' '],  // {{email_client}}
  5972.                         ['parameter_name' => 'telephone_client''text' => $data['phone'] ?? ' '],  // {{telephone_client}}
  5973.                         ['parameter_name' => 'date_lead''text' => $lead->getDate()->format('d/m/Y H:i')],  // {{date_lead}}
  5974.                         ['parameter_name' => 'code_postal''text' => $data['postalCode'] ?? ' '],  // {{code_postal}}
  5975.                         ['parameter_name' => 'nombre_centres''text' => $lead->getCentersCount() ?? '0'],  // {{nombre_centres}}
  5976.                     ],
  5977.                     'button' => $relativeUrl,  // <--- seulement le chemin dynamique
  5978.                 ]
  5979.             );
  5980.         }
  5981.     }
  5982.     /**
  5983.      * Get coordinates from the postal code using the database.
  5984.      */
  5985.     private function getCoordinatesFromPostalCode(string $postalCode): array
  5986.     {
  5987.         $region $this->entityManager
  5988.             ->getRepository(RegionDepartment::class)
  5989.             ->findOneBy(['codePostal' => $postalCode]);
  5990.         if ($region) {
  5991.             return [
  5992.                 'latitude' => $region->getLatitude(),
  5993.                 'longitude' => $region->getLongitude(),
  5994.             ];
  5995.         }
  5996.         return [
  5997.             'latitude' => null,
  5998.             'longitude' => null,
  5999.         ];
  6000.     }
  6001.     /**
  6002.      * Get the department code from the code postal
  6003.      */
  6004.     private function getDepartmentFromPostalCode(string $postalCode): ?array
  6005.     {
  6006.         $region $this->entityManager
  6007.             ->getRepository(RegionDepartment::class)
  6008.             ->findOneBy(['codePostal' => $postalCode]);
  6009.         if ($region) {
  6010.             return [
  6011.                 'departmentCode' => $region->getCodeDepartement(),
  6012.                 'departmentName' => $region->getNomDepartement(),
  6013.                 'regionCode' => $region->getCodeRegion(),
  6014.                 'regionName' => $region->getNomRegion(),
  6015.                 'city' => $region->getNomCommunePostal(),
  6016.             ];
  6017.         }
  6018.         return null;
  6019.     }
  6020.     /**
  6021.      * 
  6022.      * @Route("/giuili-admin/lead/{leadId}/centre/{centreId}", name="showLeadCentre", methods={"GET"})
  6023.      */
  6024.     public function showLeadCentre(int $leadIdCentre $centreId): Response
  6025.     {
  6026.         // dd("tets");
  6027.         $center $centres $this->getDoctrine()
  6028.             ->getRepository(AudioCentre::class)
  6029.             ->findOneBy(['id_centre' => $centreId->getId()]);
  6030.         $audio $center->getIdAudio();
  6031.         $motifs $this->getDoctrine()->getRepository(AudioMotif::class)
  6032.             ->findBy(['id_audio' => $audio'isDeleted' => 0]);
  6033.         return $this->render('easyadmin/leadRdv/centre_show.html.twig', [
  6034.             'audio' => $audio,
  6035.             'leadId' => $leadId,
  6036.             'centreId' => $centreId,
  6037.             'motifs' => $motifs,
  6038.         ]);
  6039.     }
  6040.     /**
  6041.      * @Route("/rdv-easyadmin", name="postRdvEasyAdmin", methods={"POST"})
  6042.      */
  6043.     public function postRdvEasyAdmin(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendarRdvSmsService $rdvSmsAppointmentCallService $Callservice): Response
  6044.     {
  6045.         $data json_decode($request->getContent(), true);
  6046.         $entityManager $this->getDoctrine()->getManager();
  6047.         $audio $this->getDoctrine()
  6048.             ->getRepository(Audio::class)
  6049.             ->findOneBy(['id' => $data["audio_id"]]);
  6050.         $leadRdv =   $this->getDoctrine()->getRepository(LeadRdv::class)
  6051.             ->find($data["lead_id"]);
  6052.         $client $this->getDoctrine()->getRepository(Client::class)
  6053.             ->find($leadRdv->getClient());
  6054.         $responses = [
  6055.             'rangeAge' => $leadRdv->getRangeAge(),
  6056.             'situations' =>  implode(", "$leadRdv->getSituationsGene()),
  6057.             'equipeAppareil' => $leadRdv->getEquipeAppareil(),
  6058.             'durationEquipe' => $leadRdv->getDurationEquipeAppareil(),
  6059.             'bilanAuditif' => $leadRdv->getBilanAuditif(),
  6060.             'ordonance' => $leadRdv->getOrdonance(),
  6061.             'dateOrdonance' => $leadRdv->getDateOrdonance(),
  6062.             'canMove' => $leadRdv->getCanMove(),
  6063.         ];
  6064.         // makes the rdv
  6065.         $rdv = new Rdv();
  6066.         $rdv->setIdAudio($audio);
  6067.         if (isset($proche)) {
  6068.             $rdv->setIdProche($proche);
  6069.         }
  6070.         if (isset($data["client_id_temp"])) {
  6071.             $rdv->setIdClientTemp($client);
  6072.         } else {
  6073.             $rdv->setIdClient($client);
  6074.         }
  6075.         $rdv->setIsMyaudio(true);
  6076.         if (isset($data["isRdvLead"])) {
  6077.             $rdv->setIsRdvLp(true);
  6078.         }
  6079.         if (isset($data["isRdvRapide"])) {
  6080.             $rdv->setIsRdvRapide(true);
  6081.         }
  6082.         if (isset($data["duree"])) {
  6083.             $rdv->setDuration($data["duree"]);
  6084.         }
  6085.         if (isset($data["color"])) {
  6086.             $rdv->setColor($data["color"]);
  6087.         }
  6088.         /** @var Centre */
  6089.         if (isset($data["centre_id"])) {
  6090.             $centre $this->getDoctrine()
  6091.                 ->getRepository(Centre::class)
  6092.                 ->findOneBy(['id' => $data["centre_id"]]);
  6093.             if ($centre == null) {
  6094.                 return new Response(json_encode(([
  6095.                     'message' => 'Error, no centre found at this id',
  6096.                     'path' => 'src/Controller/RdvController.php',
  6097.                     "status" => 400,
  6098.                 ])), 400);
  6099.             }
  6100.             /** @var AudioCentre */
  6101.             $liaison $this->getDoctrine()
  6102.                 ->getRepository(AudioCentre::class)
  6103.                 ->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
  6104.             if ($liaison == null) {
  6105.                 return new Response(json_encode(([
  6106.                     'message' => 'Error, audio isnt part of the centre',
  6107.                     'path' => 'src/Controller/RdvController.php',
  6108.                     "status" => 400,
  6109.                 ])), 400);
  6110.             }
  6111.             $rdv->setIdCentre($centre);
  6112.         } elseif (isset($data["lieu_id"]) && $audio->getIsIndie()) {
  6113.             // tries to set the lieu if it's an audio indie
  6114.             $lieu $this->getDoctrine()
  6115.                 ->getRepository(Lieu::class)
  6116.                 ->findOneBy(['id' => $data["lieu_id"], 'id_gerant' => $data["audio_id"]]);
  6117.             if ($lieu == null) {
  6118.                 return new Response(json_encode(([
  6119.                     'message' => 'Error, no lieu found at this id',
  6120.                     'path' => 'src/Controller/RdvController.php',
  6121.                     "status" => 400,
  6122.                 ])), 400);
  6123.             }
  6124.             $rdv->setIdLieu($lieu);
  6125.         } else {
  6126.             return new Response(json_encode(([
  6127.                 'message' => 'Error, no lieu/centre id',
  6128.                 'path' => 'src/Controller/RdvController.php',
  6129.                 "status" => 400,
  6130.             ])), 400);
  6131.         }
  6132.         /** @var Motif */
  6133.         $motif $this->getDoctrine()
  6134.             ->getRepository(Motif::class)
  6135.             ->find($data["motif_id"]);
  6136.         if ($motif == null) {
  6137.             return new Response(json_encode(([
  6138.                 'message' => 'Error, no motif found at this id',
  6139.                 'path' => 'src/Controller/RdvController.php',
  6140.                 "status" => 400,
  6141.             ])), 400);
  6142.         }
  6143.         /** @var AudioMotif */
  6144.         $audioMotif $this->getDoctrine()
  6145.             ->getRepository(AudioMotif::class)
  6146.             ->findOneBy(["id_audio" => $audio->getId(), "id_motif" => $data["motif_id"]]);
  6147.         if ($audioMotif == null) {
  6148.             return new Response(json_encode(([
  6149.                 'message' => 'Error, no motif of this id found at this audio',
  6150.                 'path' => 'src/Controller/RdvController.php',
  6151.                 "status" => 400,
  6152.             ])), 400);
  6153.         }
  6154.         // remove the taken schedule by rdv to make sure there is no overlap
  6155.         $data["date"] = str_replace("h"":"$data["date"]);
  6156.         $date \DateTime::createFromFormat("Y-m-d\TH:i"$data["date"]);
  6157.         if (isset($data["note"])) {
  6158.             $rdv->setNote($data["note"]);
  6159.         }
  6160.         $date \DateTime::createFromFormat("Y-m-d\TH:i"$data["date"]);
  6161.         $rdv->setDate($date);
  6162.         $rdv->setDateCreation(\DateTime::createFromFormat("d/m/Y H:i"date('d/m/Y H:i')));
  6163.         /** @var EtatRdv */
  6164.         $etat $this->getDoctrine()
  6165.             ->getRepository(EtatRdv::class)
  6166.             ->findOneBy(['id' => $data["etat_id"]]);
  6167.         if ($etat == null) {
  6168.             return new Response(json_encode(([
  6169.                 'message' => 'Error, no etat found at this id',
  6170.                 'path' => 'src/Controller/RdvController.php',
  6171.                 "status" => 400,
  6172.             ])), 400);
  6173.         }
  6174.         $rdv->setIdEtat($etat);
  6175.         $rdv->setIdMotif($motif);
  6176.         $rdv->setIsAbsence(0);
  6177.         $rdv->setCacher(0);
  6178.         $entityManager $this->getDoctrine()->getManager();
  6179.         $entityManager->persist($rdv);
  6180.         $leadRdv->setRdv($rdv);
  6181.         $leadStatus $this->entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'rdv_valider']);
  6182.         $leadRdv->setLeadStatus($leadStatus);
  6183.         $entityManager->flush();
  6184.         /// SMSEMAIL A décommenter pour autoriser l'envoi de sms / email à la création de rdv par l'audio / le client SMSEMAIL ///
  6185.         $date $rdv->getDate();
  6186.         $smsDate $date->format('d-m-Y H:i');
  6187.         $locale 'fr_FR';
  6188.         $formatter = new IntlDateFormatter(
  6189.             $locale,
  6190.             IntlDateFormatter::FULL,
  6191.             IntlDateFormatter::SHORT,
  6192.             null,
  6193.             IntlDateFormatter::GREGORIAN,
  6194.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  6195.         );
  6196.         $smsDateLongFormat $formatter->format($date);
  6197.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  6198.         $client->setIdCentre($rdv->getIdCentre());
  6199.         $client->setIdAudio($rdv->getIdAudio());
  6200.         $entityManager->persist($client);
  6201.         $entityManager->flush();
  6202.         // client notif mail Sms
  6203.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  6204.         $frenchDate ucfirst($frenchDate);
  6205.         $params = array(
  6206.             "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  6207.             "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  6208.             "date" => $smsDateLongFormat,
  6209.             "RdvDate" => $smsDateLongFormat,
  6210.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  6211.             "centerName" => $rdv->getIdCentre()->getName(),
  6212.             "prenom" => $client->getName(),
  6213.             "centerAddress" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  6214.             "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  6215.             'motif' => $rdv->getIdMotif()->getTitre(),
  6216.             "centerCity" => $rdv->getIdCentre()->getCity(),
  6217.             "audioName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  6218.             'titre' => "Votre rendez-vous est validé le " substr($smsDate010) . " à "  substr($smsDate1115),
  6219.             "position" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  6220.             "address" => $rdv->getIdCentre()->getAddress(),
  6221.             "postal" => $rdv->getIdCentre()->getPostale(),
  6222.             "city" => $rdv->getIdCentre()->getCity(),
  6223.             "clientEmail" => $client->getMail(),
  6224.             "clientPassword" => isset($data["passwordGenerated"]) ? $data["passwordGenerated"] : null,
  6225.             "clientAddress" => $client->getAddress(),
  6226.             "clientPostal" => $client->getPostal(),
  6227.             "clientCity" => $client->getCity(),
  6228.             "audioName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  6229.             "frenchDate" => $frenchDate,
  6230.             "heure" => substr($smsDate1115),
  6231.             "centerName" => $rdv->getIdCentre()->getName(),
  6232.             "audioMail" => $rdv->getIdAudio()->getMail(),
  6233.             "modifUrl" => "{$_ENV['BASE_client']}mes-rendez-vous",
  6234.         );
  6235.         $paramsPatient $params;
  6236.         $isNew false;
  6237.         if (isset($data["isLead"]) && isset($data["passwordGenerated"]) != null) {
  6238.             $subject "✅Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  6239.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject189);
  6240.             $isNew true;
  6241.         } else {
  6242.             $subject "Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  6243.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject181);
  6244.         }
  6245.         $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.";
  6246.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  6247.         // audio Notif mail SMS
  6248.         $birthday $rdv->getIdClient()->getBirthdate();
  6249.         $params = array(
  6250.             "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  6251.             "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  6252.             "date" => substr($smsDate010),
  6253.             "heure" => substr($smsDate1115),
  6254.             "mail" => $client->getMail(),
  6255.             "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  6256.             'telClient' => $client->getPhone(),
  6257.             'phone' => $client->getPhone(),
  6258.             'clientCivilite' => $client->getCivilite(),
  6259.             'clientNom' => $client->getLastname(),
  6260.             'clientPrenom' => $client->getName(),
  6261.             'clientPostal' => $client->getPostal(),
  6262.             'clientMail' => $client->getMail(),
  6263.             'clientPhone' => $client->getPhone(),
  6264.             'motif' => $rdv->getIdMotif()->getTitre(),
  6265.             'birthdate' => $client->getBirthdate() ? $client->getBirthdate()->format("d/m/Y") : null,
  6266.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  6267.             'centerName' => $rdv->getIdCentre()->getName(),
  6268.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  6269.             'centerCity' => $rdv->getIdCentre()->getCity(),
  6270.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  6271.             'idPatient' => $client->getId(),
  6272.             'proUrl' => "{$_ENV['BASE_logiciel']}",
  6273.             'frenchDate' => $frenchDate,
  6274.             'responses' => $responses,
  6275.         );
  6276.         $templateEmail 182;
  6277.         if (!empty($data['canMove'])) {
  6278.             $templateEmail 197;
  6279.         }
  6280.         $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  6281.         $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  6282.         if ($rdv->getIdAudio()->getConfirmRdvMail()) {
  6283.             $subject "✅ Nouveau Rendez-vous My Audio le " $frenchDate " à " substr($smsDate1115);
  6284.             $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject$templateEmail);
  6285.         }
  6286.         if ($rdv->getIdAudio()->getConfirmRdvSms()) {
  6287.             $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.";
  6288.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  6289.         }
  6290.         $age null;
  6291.         if ($client->getBirthdate()) {
  6292.             $age $client->getBirthdate()->diff(new \DateTime())->y;
  6293.         }
  6294.         // Génère le PDF à partir d’un template
  6295.         $pdfContent $this->generatePdf(
  6296.             'pdf/rdv_recap.html.twig',
  6297.             [
  6298.                 'id' => $client->getId() ?? '',
  6299.                 'nom' => $client->getName() ?? '',
  6300.                 'prenom' => $client->getLastname() ?? '',
  6301.                 'birthday' =>  $client->getBirthdate() ? $client->getBirthdate()->format("d/m/Y") : null,
  6302.                 'age' => $age,
  6303.                 'adresse' => $client->getAddress() ?? '',
  6304.                 'postal' => $client->getPostal() ?? '',
  6305.                 'city' => $client->getCity() ?? '',
  6306.                 'phone' => $client->getPhone() ?? '',
  6307.                 'mail' => $client->getMail() ?? '',
  6308.                 'centerName' => $rdv->getIdCentre()->getName() ?? '',
  6309.                 "date" => substr($smsDate010) ?? '',
  6310.                 "heure" => substr($smsDate1115) ?? '',
  6311.                 'duration' => $rdv->getDuration(),
  6312.                 "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  6313.                 'motif' => $rdv->getIdMotif() ? $rdv->getIdMotif()->getTitre() : '',
  6314.                 'situations' => $this->formatImploded($leadRdv->getSituationsGene()),
  6315.                 'IntensiteGen' => $leadRdv->getIntensiteGene() ?? '',
  6316.                 'devicePref' => $this->formatImploded($leadRdv->getPreferenceDevice()),
  6317.                 'deviceModelPref' =>  implode(", "$leadRdv->getDeviceModelPreference()),
  6318.                 'criterePrincipal' => $this->formatImploded($leadRdv->getCriterePrincipal()),
  6319.                 'accoupheneCote' =>  $leadRdv->getAcoupheneCote() ?? '',
  6320.                 'originePerte' => $this->formatImploded($leadRdv->getOriginePerte()),
  6321.                 'diabete' =>  $leadRdv->getDiabete() ?? '',
  6322.                 'hypertension' =>  $leadRdv->getHypertension() ?? '',
  6323.                 'mutuelle' =>  $leadRdv->getMutuelle() ?? '',
  6324.                 'nameMutuelle' =>  $leadRdv->getNameMutuelle() ?? '',
  6325.                 'priseEnCharge' => $leadRdv->getPriseEnCharge() ?? '',
  6326.                 'budget' => $leadRdv->getBudget() ?? '',
  6327.                 'equipeAppareil' => $leadRdv->getEquipeAppareil() ?? '',
  6328.                 'durationEquipe' => $leadRdv->getDurationEquipeAppareil() ?? '',
  6329.                 'bilanAuditif' => $leadRdv->getBilanAuditif() ?? '',
  6330.                 'ordonance' => $leadRdv->getOrdonance() ?? '',
  6331.                 'dateOrdonance' => $leadRdv->getDateOrdonance() ?? '',
  6332.                 'canMove' => $leadRdv->getCanMove() ?? '',
  6333.                 'comment' => $leadRdv->getComment() ?? '',
  6334.             ],
  6335.             $this->getParameter('kernel.project_dir') . '/public/assets/pdf/recap-rdv-myaudio.pdf'
  6336.         );
  6337.         $this->sendEmailWithPdfAttachmentThenDelete(
  6338.             $params,
  6339.             $mailAudio,
  6340.             $client->getName(),
  6341.             $subject,
  6342.             $templateEmail// ID du template Sendinblue
  6343.             $pdfContent
  6344.         );
  6345.         // send notif to admin
  6346.         $paramsSourceLead = [
  6347.             'trafficSource' => "EasyAdmin",
  6348.         ];
  6349.         $paramsAdmin = array(
  6350.             "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  6351.             "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  6352.             "RdvDate" => substr($smsDate010),
  6353.             "heure" => substr($smsDate1115),
  6354.             "clientMail" => $client->getMail(),
  6355.             "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  6356.             'telClient' => $client->getPhone(),
  6357.             'clientNom' => $client->getLastname(),
  6358.             'clientPrenom' => $client->getName(),
  6359.             'clientCivilite' => $client->getCivilite(),
  6360.             'clientPostal' => $client->getPostal(),
  6361.             'clientPhone' => $client->getPhone(),
  6362.             'motif' => $rdv->getIdMotif()->getTitre(),
  6363.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  6364.             'centerName' => $rdv->getIdCentre()->getName(),
  6365.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  6366.             'centerCity' => $rdv->getIdCentre()->getCity(),
  6367.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  6368.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  6369.             'date' => substr($smsDate010),
  6370.             'urlApi' => "{$_ENV['BASE_API']}",
  6371.             'clientId' => $client->getId(),
  6372.             'centerId' => $rdv->getIdCentre()->getId(),
  6373.             'frenchDate' => $frenchDate,
  6374.             'responses' => $responses,
  6375.             'paramsSourceLead' => $paramsSourceLead
  6376.         );
  6377.         $subject "Nouveau RDV MA | RR - " $rdv->getIdCentre()->getName();
  6378.         $templateEmail 183;
  6379.         if (!empty($data['canMove'])) {
  6380.             $templateEmail 190;
  6381.         }
  6382.         $publicFunction->sendEmail($paramsAdmin"contact@myaudio.fr""my audio"$subject$templateEmail);
  6383.         $publicFunction->sendEmail($paramsAdmin"lead.myaudio@gmail.com""my audio"$subject$templateEmail);
  6384.         $specificSubscription $this->getDoctrine()
  6385.              ->getRepository(SpecificSubscription::class)
  6386.              ->findOneBy(['audio' => $audio]);
  6387.       if ($specificSubscription && $specificSubscription->getContractCategory()) {
  6388.         $contractCategory $specificSubscription->getContractCategory();
  6389.       if ($contractCategory->getName() === "OPTICAL CENTER SUCCURSALE") {
  6390.         $publicFunction->sendEmail($paramsAdmin"christel.montagne@optical-center.com""my audio"$subject246);
  6391.          }
  6392.        }
  6393.         try {
  6394.             $Callservice->handleCallCenterAfterRdv(
  6395.                 $rdv
  6396.             );
  6397.             $rdv->setIsNotificationRdvCallSent(1);
  6398.             $this->entityManager->flush();
  6399.         } catch (\Exception $e) {
  6400.             $this->logger->error("Erreur lors de l'appel de notification pour le RDV #{$rdv->getId()}: " $e->getMessage());
  6401.         }
  6402.         // google calendar post
  6403.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  6404.             ->findBy(array('audio' => $audio->getId()));
  6405.         $data['rdv'] = $rdv->getId();
  6406.         foreach ($synchronisations as $synchronisation) {
  6407.             if (!$synchronisation->getIsDeleted()) {
  6408.                 $googleCalendar->checkAndRefreshAccessToken($synchronisation);
  6409.                 $googleCalendar->createEvent($synchronisation$data);
  6410.             }
  6411.         }
  6412.         return new Response(json_encode(([
  6413.             "id" => $rdv->getId(),
  6414.             "motif_id" => $rdv->getIdMotif()->getId(),
  6415.             "audio_id" => $rdv->getIdAudio()->getId(),
  6416.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  6417.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  6418.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  6419.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  6420.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  6421.             "testclient" => $rdv->getTestClient() ? [
  6422.                 "result" => $rdv->getTestClient()->getResultTonal(),
  6423.                 "date" => $rdv->getTestClient()->getDate(),
  6424.                 "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  6425.             ] : null,
  6426.             "duration" => $audioMotif->getDuration(),
  6427.             "consigne" => $audioMotif->getConsigne(),
  6428.             "etat_id" => $rdv->getIdEtat()->getId(),
  6429.             "date" => $rdv->getDate(),
  6430.             "comment" => $rdv->getComment(),
  6431.             "centerName" => $rdv->getIdCentre()->getName(),
  6432.             "review" => $rdv->getReview(),
  6433.             "note" => $rdv->getNote(),
  6434.             "status" => 200,
  6435.             "paramsPatient" => $paramsPatient,
  6436.             "isNew" => $isNew,
  6437.         ])));
  6438.     }
  6439.     private function generatePdf(string $template, array $data = [], string $outputPath): string
  6440.     {
  6441.         // Render le contenu HTML avec Twig
  6442.         $html $this->twig->render($template$data);
  6443.         // Configurer Dompdf
  6444.         $options = new Options();
  6445.         $options->set('defaultFont''Arial');
  6446.         $dompdf = new Dompdf($options);
  6447.         $dompdf->loadHtml($html);
  6448.         $dompdf->setPaper('A4''portrait');
  6449.         $dompdf->render();
  6450.         // Sauvegarder le PDF
  6451.         file_put_contents($outputPath$dompdf->output());
  6452.         return $outputPath// Renvoie le chemin du fichier PDF généré
  6453.     }
  6454.     private function sendEmailWithPdfAttachmentThenDelete(
  6455.         array $params,
  6456.         string $mail,
  6457.         string $name,
  6458.         string $subject,
  6459.         int $templateId,
  6460.         string $pdfFilePath
  6461.     ): void {
  6462.         // Lire et encoder le contenu du PDF
  6463.         $attachment = [
  6464.             "name" => basename($pdfFilePath),
  6465.             "content" => base64_encode(file_get_contents($pdfFilePath)),
  6466.         ];
  6467.         // Construire les données pour l’API Sendinblue
  6468.         $data = [
  6469.             "sender" => [
  6470.                 "email" => 'noreply@myaudio.fr',
  6471.                 "name" => 'My Audio',
  6472.             ],
  6473.             "to" => [
  6474.                 [
  6475.                     "email" => $mail,
  6476.                     "name" => $name,
  6477.                 ],
  6478.             ],
  6479.             "subject" => $subject,
  6480.             "templateId" => $templateId,
  6481.             "params" => $params,
  6482.             "attachment" => [$attachment],
  6483.         ];
  6484.         // Envoi via cURL
  6485.         $ch curl_init();
  6486.         curl_setopt($chCURLOPT_URL'https://api.sendinblue.com/v3/smtp/email');
  6487.         curl_setopt($chCURLOPT_RETURNTRANSFER1);
  6488.         curl_setopt($chCURLOPT_POST1);
  6489.         curl_setopt($chCURLOPT_POSTFIELDSjson_encode($data));
  6490.         $headers = [
  6491.             'Accept: application/json',
  6492.             'Api-Key: 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',
  6493.             'Content-Type: application/json',
  6494.         ];
  6495.         curl_setopt($chCURLOPT_HTTPHEADER$headers);
  6496.         $result curl_exec($ch);
  6497.         if (curl_errno($ch)) {
  6498.             echo 'Erreur email : ' curl_error($ch);
  6499.         }
  6500.         curl_close($ch);
  6501.         // Supprimer le PDF après envoi
  6502.         if (file_exists($pdfFilePath)) {
  6503.             unlink($pdfFilePath);
  6504.         }
  6505.     }
  6506.     private function formatImploded(array $data): string
  6507.     {
  6508.         return implode(', 'array_map(function ($item) {
  6509.             return str_replace('_'' '$item);
  6510.         }, $data));
  6511.     }
  6512.     /**
  6513.      * 
  6514.      * @Route("/admin/rdv/export-pdf-form", name="admin_rdv_export_pdf_form", methods={"GET", "POST"})
  6515.      */
  6516.     public function exportPdfForm(Request $request): Response
  6517.     {
  6518.         $form $this->createFormBuilder()
  6519.             ->add('startDate'\Symfony\Component\Form\Extension\Core\Type\DateType::class, [
  6520.                 'label' => 'Date de début',
  6521.                 'widget' => 'single_text',
  6522.                 'html5' => true,
  6523.                 'required' => true,
  6524.             ])
  6525.             ->add('endDate'\Symfony\Component\Form\Extension\Core\Type\DateType::class, [
  6526.                 'label' => 'Date de fin',
  6527.                 'widget' => 'single_text',
  6528.                 'html5' => true,
  6529.                 'required' => true,
  6530.             ])
  6531.             ->add('format'\Symfony\Component\Form\Extension\Core\Type\ChoiceType::class, [
  6532.                 'label' => 'Format d\'export',
  6533.                 'choices' => [
  6534.                     'PDF' => 'pdf',
  6535.                     'Excel' => 'excel',
  6536.                 ],
  6537.                 'expanded' => false,
  6538.                 'multiple' => false,
  6539.                 'required' => true,
  6540.             ])
  6541.             ->getForm();
  6542.         //dd($request);
  6543.         $form->handleRequest($request);
  6544.         if ($form->isSubmitted() && $form->isValid()) {
  6545.             $data $form->getData();
  6546.             $start $data['startDate']->format('Y-m-d');
  6547.             $end $data['endDate']->format('Y-m-d');
  6548.             if ($data['format'] === 'pdf') {
  6549.                 return $this->redirectToRoute('admin_rdv_export_pdf', [
  6550.                     'startDate' => $start,
  6551.                     'endDate' => $end,
  6552.                 ]);
  6553.             } else {
  6554.                 return $this->redirectToRoute('admin_rdv_export_excel', [
  6555.                     'startDate' => $start,
  6556.                     'endDate' => $end,
  6557.                 ]);
  6558.             }
  6559.         }
  6560.         return $this->render('easyadmin/rdv/export_pdf_form.html.twig', [
  6561.             'form' => $form->createView(),
  6562.         ]);
  6563.     }
  6564.     /**
  6565.      * 
  6566.      * @Route("/optical/rdv/export-pdf-form", name="optical_rdv_export_pdf_form", methods={"GET", "POST"})
  6567.      */
  6568.     public function exportOpticalPdfForm(Request $request): Response
  6569.     {
  6570.         $form $this->createFormBuilder()
  6571.             ->add('startDate'\Symfony\Component\Form\Extension\Core\Type\DateType::class, [
  6572.                 'label' => 'Date de début',
  6573.                 'widget' => 'single_text',
  6574.                 'html5' => true,
  6575.                 'required' => true,
  6576.             ])
  6577.             ->add('endDate'\Symfony\Component\Form\Extension\Core\Type\DateType::class, [
  6578.                 'label' => 'Date de fin',
  6579.                 'widget' => 'single_text',
  6580.                 'html5' => true,
  6581.                 'required' => true,
  6582.             ])
  6583.             ->add('format'\Symfony\Component\Form\Extension\Core\Type\ChoiceType::class, [
  6584.                 'label' => 'Format d\'export',
  6585.                 'choices' => [
  6586.                     'PDF' => 'pdf',
  6587.                     'Excel' => 'excel',
  6588.                 ],
  6589.                 'expanded' => false,
  6590.                 'multiple' => false,
  6591.                 'required' => true,
  6592.             ])
  6593.             ->getForm();
  6594.         //dd($request);
  6595.         $form->handleRequest($request);
  6596.         if ($form->isSubmitted() && $form->isValid()) {
  6597.             $data $form->getData();
  6598.             $start $data['startDate']->format('Y-m-d');
  6599.             $end $data['endDate']->format('Y-m-d');
  6600.             if ($data['format'] === 'pdf') {
  6601.                 return $this->redirectToRoute('optical_rdv_export_pdf', [
  6602.                     'startDate' => $start,
  6603.                     'endDate' => $end,
  6604.                 ]);
  6605.             } else {
  6606.                 return $this->redirectToRoute('optical_rdv_export_excel', [
  6607.                     'startDate' => $start,
  6608.                     'endDate' => $end,
  6609.                 ]);
  6610.             }
  6611.         }
  6612.         return $this->render('easyadmin/rdv/export_pdf_form.html.twig', [
  6613.             'form' => $form->createView(),
  6614.         ]);
  6615.     }
  6616.     /**
  6617.      * @Route("/admin/lead-rdv/update-status", name="admin_lead_rdv_update_status", methods={"POST"})
  6618.      */
  6619.     public function updateStatus(Request $request): JsonResponse
  6620.     {
  6621.         // Récupérer les données envoyées en AJAX
  6622.         $data json_decode($request->getContent(), true);
  6623.         $leadId $data['leadId'] ?? null;
  6624.         $statusId $data['statusId'] ?? null;
  6625.         if (!$leadId || !$statusId) {
  6626.             return new JsonResponse(['success' => false'message' => 'Données manquantes'], 400);
  6627.         }
  6628.         // Récupérer le lead et le statut
  6629.         $lead $this->entityManager->getRepository(LeadRdv::class)->find($leadId);
  6630.         $status $this->entityManager->getRepository(LeadStatus::class)->find($statusId);
  6631.         if (!$lead || !$status) {
  6632.             return new JsonResponse(['success' => false'message' => 'Lead ou statut introuvable'], 404);
  6633.         }
  6634.         // Mettre à jour le statut du lead
  6635.         $lead->setLeadStatus($status);
  6636.         $this->entityManager->flush();
  6637.         return new JsonResponse(['success' => true]);
  6638.     }
  6639.     /**
  6640.      * @Route("/admin/rdv/update-client-status", name="admin_rdv_update_client_status", methods={"POST"})
  6641.      */
  6642.     public function updateClientStatus(Request $request): JsonResponse
  6643.     {
  6644.         $data json_decode($request->getContent(), true);
  6645.         $rdvId $data['rdvId'] ?? null;
  6646.         $statusId $data['statusId'] ?? null;
  6647.         if (!$rdvId || !$statusId) {
  6648.             return new JsonResponse(['success' => false'message' => 'Données manquantes'], 400);
  6649.         }
  6650.         // Récupérer le RDV
  6651.         $rdv $this->entityManager->getRepository(Rdv::class)->find($rdvId);
  6652.         if (!$rdv) {
  6653.             return new JsonResponse(['success' => false'message' => 'RDV non trouvé'], 404);
  6654.         }
  6655.         // Récupérer le statut
  6656.         $clientStatus $this->entityManager->getRepository(ClientStatus::class)->find($statusId);
  6657.         if (!$clientStatus) {
  6658.             return new JsonResponse(['success' => false'message' => 'Statut non trouvé'], 404);
  6659.         }
  6660.         // Mettre à jour le client
  6661.         $client $rdv->getIdClient();
  6662.         if ($client) {
  6663.             $client->setClientStatus($clientStatus);
  6664.             $this->entityManager->flush();
  6665.             // Si le statut est "Facturé", lancer la facturation
  6666.             if ((int)$statusId === 2) {
  6667.                 // Réutiliser la méthode de facturation existante
  6668.                 $crudController $this->container->get(RdvMyAudioCrudController::class);
  6669.                 $crudController->billing($rdv);
  6670.             }
  6671.             return new JsonResponse(['success' => true]);
  6672.         }
  6673.         return new JsonResponse(['success' => false'message' => 'Client non trouvé'], 404);
  6674.     }
  6675.     /**
  6676.      * @Route("/admin/rdv/update-rdv-status", name="admin_rdv_update_status", methods={"POST"})
  6677.      */
  6678.     public function updateRdvStatus(Request $requestEntityManagerInterface $entityManager): JsonResponse
  6679.     {
  6680.         $data json_decode($request->getContent(), true);
  6681.         $rdvId $data['rdvId'] ?? null;
  6682.         $statusId $data['statusId'] ?? null;
  6683.         if (!$rdvId || !$statusId) {
  6684.             return new JsonResponse(['success' => false'message' => 'Données manquantes'], 400);
  6685.         }
  6686.         // Récupérer le RDV
  6687.         $rdv $entityManager->getRepository(Rdv::class)->find($rdvId);
  6688.         if (!$rdv) {
  6689.             return new JsonResponse(['success' => false'message' => 'RDV non trouvé'], 404);
  6690.         }
  6691.         // Récupérer le statut
  6692.         $etatRdv $entityManager->getRepository(EtatRdv::class)->find($statusId);
  6693.         if (!$etatRdv) {
  6694.             return new JsonResponse(['success' => false'message' => 'Statut non trouvé'], 404);
  6695.         }
  6696.         // Mettre à jour le statut du RDV
  6697.         $rdv->setIdEtat($etatRdv);
  6698.         $entityManager->flush();
  6699.         return new JsonResponse(['success' => true]);
  6700.     }
  6701.     /**
  6702.      * @Route("/admin/rdv/export-pdf/{startDate}/{endDate}", name="admin_rdv_export_pdf", methods={"GET"})
  6703.      */
  6704.     public function exportPdfFromDate(string $startDatestring $endDateKernelInterface $kernel): Response
  6705.     {
  6706.         $start = new \DateTimeImmutable($startDate);
  6707.         $end = new \DateTimeImmutable($endDate);
  6708.         $today = new \DateTimeImmutable();
  6709.         $rdvs $this->rdvRepository->findBySinceDateAndMyAudio($start$end);
  6710.         $html "
  6711.     <html>
  6712.     <head>
  6713.         <style>
  6714.             body { font-family: Arial, sans-serif; font-size: 13px; }
  6715.             table { width: 100%; border-collapse: collapse; font-size: 11px; }
  6716.             th, td { border: 1px solid #000; padding: 5px; text-align: left; }
  6717.             th { font-weight: bold; }
  6718.             h1 { font-size: 14px; }
  6719.         </style>
  6720.     </head>
  6721.     <body>
  6722.         <h1>Rendez-vous My Audio du " $start->format('d/m/Y') . " au " $end->format('d/m/Y') . "</h1>
  6723.         <table cellspacing='0' cellpadding='5'>
  6724.             <thead>
  6725.                 <tr>
  6726.                     <th>ID du RDV</th>
  6727.                     <th>Date du RDV</th>
  6728.                     <th>Jours écoulés</th>
  6729.                     <th>Statut RDV</th>
  6730.                     <th>Nom patient</th>
  6731.                     <th>Téléphone patient</th>
  6732.                     <th>Statut patient</th>
  6733.                     <th>Centre</th>
  6734.                     <th>Téléphone Centre</th>
  6735.                     <th>Adresse</th>
  6736.                     <th>Nom Audio</th>
  6737.                 </tr>
  6738.             </thead>
  6739.             <tbody>";
  6740.         foreach ($rdvs as $rdv) {
  6741.             $dateRdv $rdv->getDate();
  6742.             $joursEcoules $dateRdv->diff($today)->days;
  6743.             $client $rdv->getIdClient();
  6744.             $centre $rdv->getIdCentre();
  6745.             $etat $rdv->getIdEtat();
  6746.             $audio $rdv->getIdAudio();
  6747.             $html .= "<tr>
  6748.             <td>" $rdv->getId() . "</td>
  6749.             <td>" $dateRdv->format('d/m/Y H:i') . "</td>
  6750.             <td>" $joursEcoules " jours</td>
  6751.             <td>" . ($etat htmlspecialchars($etat->getLibelle()) : 'Non défini') . "</td>
  6752.             <td>" . ($client htmlspecialchars($client->getName() . ' ' $client->getLastname()) : '') . "</td>
  6753.             <td>" . ($client htmlspecialchars($client->getPhone()) : '') . "</td>
  6754.             <td>" . ($client && $client->getClientStatus() ? htmlspecialchars($client->getClientStatus()->getLibelle()) : 'Non défini') . "</td>
  6755.             <td>" . ($centre htmlspecialchars($centre->getName()) : '') . "</td>
  6756.             <td>" . ($centre htmlspecialchars($centre->getPhone()) : '') . "</td>
  6757.             <td>" . ($centre htmlspecialchars($centre->getAddress() . ', ' $centre->getPostale() . ' ' $centre->getCity()) : '') . "</td>
  6758.             <td>" . ($audio htmlspecialchars($audio->getCivilite() . ' ' $audio->getName() . ' ' $audio->getLastname()) : '') . "</td>
  6759.         </tr>";
  6760.         }
  6761.         $html .= "</tbody></table></body></html>";
  6762.         // Configuration et rendu du PDF
  6763.         $options = new Options();
  6764.         $options->set('defaultFont''Arial');
  6765.         $dompdf = new Dompdf($options);
  6766.         $dompdf->loadHtml($html);
  6767.         $dompdf->setPaper('A4''landscape');
  6768.         $dompdf->render();
  6769.         // Création du dossier s'il n'existe pas
  6770.         $projectDir $kernel->getProjectDir();
  6771.         $outputDir $projectDir '/public/assets/pdf/rdv';
  6772.         $filesystem = new Filesystem();
  6773.         if (!$filesystem->exists($outputDir)) {
  6774.             $filesystem->mkdir($outputDir0775);
  6775.         }
  6776.         $filenameDate $start->format('Y-m-d') . '_to_' $end->format('Y-m-d');
  6777.         $outputPath "$outputDir/rdvs-$filenameDate.pdf";
  6778.         file_put_contents($outputPath$dompdf->output());
  6779.         return new Response($dompdf->output(), 200, [
  6780.             'Content-Type' => 'application/pdf',
  6781.             'Content-Disposition' => 'attachment; filename="rdvs-' $filenameDate '.pdf"',
  6782.         ]);
  6783.     }
  6784.     /**
  6785.      * @Route("/optical/rdv/export-pdf/{startDate}/{endDate}", name="optical_rdv_export_pdf", methods={"GET"})
  6786.      */
  6787.     public function exportOpticalPdfFromDate(string $startDatestring $endDateKernelInterface $kernel): Response
  6788.     {
  6789.         $start = new \DateTimeImmutable($startDate);
  6790.         $end = new \DateTimeImmutable($endDate);
  6791.         $today = new \DateTimeImmutable();
  6792.         $rdvs $this->rdvRepository->findOpticalBySinceDateAndMyAudio($start$end);
  6793.         $html "
  6794.     <html>
  6795.     <head>
  6796.         <style>
  6797.             body { font-family: Arial, sans-serif; font-size: 13px; }
  6798.             table { width: 100%; border-collapse: collapse; font-size: 11px; }
  6799.             th, td { border: 1px solid #000; padding: 5px; text-align: left; }
  6800.             th { font-weight: bold; }
  6801.             h1 { font-size: 14px; }
  6802.         </style>
  6803.     </head>
  6804.     <body>
  6805.         <h1>Rendez-vous My Audio du " $start->format('d/m/Y') . " au " $end->format('d/m/Y') . "</h1>
  6806.         <table cellspacing='0' cellpadding='5'>
  6807.             <thead>
  6808.                 <tr>
  6809.                     <th>ID du RDV</th>
  6810.                     <th>Date du RDV</th>
  6811.                     <th>Jours écoulés</th>
  6812.                     <th>Statut RDV</th>
  6813.                     <th>Nom patient</th>
  6814.                     <th>Téléphone patient</th>
  6815.                     <th>Statut patient</th>
  6816.                     <th>Centre</th>
  6817.                     <th>Téléphone Centre</th>
  6818.                     <th>Adresse</th>
  6819.                     <th>Nom Audio</th>
  6820.                 </tr>
  6821.             </thead>
  6822.             <tbody>";
  6823.         foreach ($rdvs as $rdv) {
  6824.             $dateRdv $rdv->getDate();
  6825.             $joursEcoules $dateRdv->diff($today)->days;
  6826.             $client $rdv->getIdClient();
  6827.             $centre $rdv->getIdCentre();
  6828.             $etat $rdv->getIdEtat();
  6829.             $audio $rdv->getIdAudio();
  6830.             $html .= "<tr>
  6831.             <td>" $rdv->getId() . "</td>
  6832.             <td>" $dateRdv->format('d/m/Y H:i') . "</td>
  6833.             <td>" $joursEcoules " jours</td>
  6834.             <td>" . ($etat htmlspecialchars($etat->getLibelle()) : 'Non défini') . "</td>
  6835.             <td>" . ($client htmlspecialchars($client->getName() . ' ' $client->getLastname()) : '') . "</td>
  6836.             <td>" . ($client htmlspecialchars($client->getPhone()) : '') . "</td>
  6837.             <td>" . ($client && $client->getClientStatus() ? htmlspecialchars($client->getClientStatus()->getLibelle()) : 'Non défini') . "</td>
  6838.             <td>" . ($centre htmlspecialchars($centre->getName()) : '') . "</td>
  6839.             <td>" . ($centre htmlspecialchars($centre->getPhone()) : '') . "</td>
  6840.             <td>" . ($centre htmlspecialchars($centre->getAddress() . ', ' $centre->getPostale() . ' ' $centre->getCity()) : '') . "</td>
  6841.             <td>" . ($audio htmlspecialchars($audio->getCivilite() . ' ' $audio->getName() . ' ' $audio->getLastname()) : '') . "</td>
  6842.         </tr>";
  6843.         }
  6844.         $html .= "</tbody></table></body></html>";
  6845.         // Configuration et rendu du PDF
  6846.         $options = new Options();
  6847.         $options->set('defaultFont''Arial');
  6848.         $dompdf = new Dompdf($options);
  6849.         $dompdf->loadHtml($html);
  6850.         $dompdf->setPaper('A4''landscape');
  6851.         $dompdf->render();
  6852.         // Création du dossier s'il n'existe pas
  6853.         $projectDir $kernel->getProjectDir();
  6854.         $outputDir $projectDir '/public/assets/pdf/rdv';
  6855.         $filesystem = new Filesystem();
  6856.         if (!$filesystem->exists($outputDir)) {
  6857.             $filesystem->mkdir($outputDir0775);
  6858.         }
  6859.         $filenameDate $start->format('Y-m-d') . '_to_' $end->format('Y-m-d');
  6860.         $outputPath "$outputDir/rdvs-$filenameDate.pdf";
  6861.         file_put_contents($outputPath$dompdf->output());
  6862.         return new Response($dompdf->output(), 200, [
  6863.             'Content-Type' => 'application/pdf',
  6864.             'Content-Disposition' => 'attachment; filename="rdvs-' $filenameDate '.pdf"',
  6865.         ]);
  6866.     }
  6867.     /**
  6868.      * 
  6869.      * @Route("/admin/rdv/export/excel/{startDate}/{endDate}", name="admin_rdv_export_excel", methods={"GET"})
  6870.      */
  6871.     public function exportExcelFromDate(string $startDatestring $endDate): Response
  6872.     {
  6873.         $start = new \DateTimeImmutable($startDate);
  6874.         $end = new \DateTimeImmutable($endDate);
  6875.         $rdvs $this->rdvRepository->findBySinceDateAndMyAudio($start$end);
  6876.         $spreadsheet = new Spreadsheet();
  6877.         $sheet $spreadsheet->getActiveSheet();
  6878.         // Headers
  6879.         $sheet->fromArray([
  6880.             'ID du RDV',
  6881.             'Date du RDV',
  6882.             'Jours écoulés',
  6883.             'Statut RDV',
  6884.             'Nom patient',
  6885.             'Téléphone patient',
  6886.             'Statut patient',
  6887.             'Centre',
  6888.             'Téléphone Centre',
  6889.             'Adresse',
  6890.             'Nom Audio'
  6891.         ], null'A1');
  6892.         $today = new \DateTimeImmutable();
  6893.         $row 2;
  6894.         foreach ($rdvs as $rdv) {
  6895.             $dateRdv $rdv->getDate();
  6896.             $joursEcoules $dateRdv->diff($today)->days;
  6897.             $client $rdv->getIdClient();
  6898.             $centre $rdv->getIdCentre();
  6899.             $etat $rdv->getIdEtat();
  6900.             $sheet->fromArray([
  6901.                 $rdv->getId(),
  6902.                 $dateRdv->format('d/m/Y H:i'),
  6903.                 $joursEcoules ' jours',
  6904.                 $etat $etat->getLibelle() : 'Non défini',
  6905.                 $client $client->getName() . ' ' $client->getLastname() : '',
  6906.                 $client $client->getPhone() : '',
  6907.                 $client && $client->getClientStatus() ? $client->getClientStatus()->getLibelle() : 'Non défini',
  6908.                 $centre $centre->getName() : '',
  6909.                 $centre $centre->getPhone() : '',
  6910.                 $centre $centre->getAddress() . ', ' $centre->getPostale() . ' ' $centre->getCity() : '',
  6911.                 $rdv->getIdAudio() ? $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastname() : '',
  6912.             ], null'A' $row);
  6913.             $row++;
  6914.         }
  6915.         $writer = new Xlsx($spreadsheet);
  6916.         $filename "rdvs-$startDate-to-$endDate.xlsx";
  6917.         // Stream the file to browser
  6918.         $response = new \Symfony\Component\HttpFoundation\StreamedResponse(function () use ($writer) {
  6919.             $writer->save('php://output');
  6920.         });
  6921.         $dispositionHeader $response->headers->makeDisposition(
  6922.             \Symfony\Component\HttpFoundation\ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  6923.             $filename
  6924.         );
  6925.         $response->headers->set('Content-Type''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  6926.         $response->headers->set('Content-Disposition'$dispositionHeader);
  6927.         return $response;
  6928.     }
  6929.     /**
  6930.      * 
  6931.      * @Route("/optical/rdv/export/excel/{startDate}/{endDate}", name="optical_rdv_export_excel", methods={"GET"})
  6932.      */
  6933.     public function exportOpticalExcelFromDate(string $startDatestring $endDate): Response
  6934.     {
  6935.         $start = new \DateTimeImmutable($startDate);
  6936.         $end = new \DateTimeImmutable($endDate);
  6937.         $rdvs $this->rdvRepository->findOpticalBySinceDateAndMyAudio($start$end);
  6938.         $spreadsheet = new Spreadsheet();
  6939.         $sheet $spreadsheet->getActiveSheet();
  6940.         // Headers
  6941.         $sheet->fromArray([
  6942.             'ID du RDV',
  6943.             'Date du RDV',
  6944.             'Jours écoulés',
  6945.             'Statut RDV',
  6946.             'Nom patient',
  6947.             'Téléphone patient',
  6948.             'Statut patient',
  6949.             'Centre',
  6950.             'Téléphone Centre',
  6951.             'Adresse',
  6952.             'Nom Audio'
  6953.         ], null'A1');
  6954.         $today = new \DateTimeImmutable();
  6955.         $row 2;
  6956.         foreach ($rdvs as $rdv) {
  6957.             $dateRdv $rdv->getDate();
  6958.             $joursEcoules $dateRdv->diff($today)->days;
  6959.             $client $rdv->getIdClient();
  6960.             $centre $rdv->getIdCentre();
  6961.             $etat $rdv->getIdEtat();
  6962.             $sheet->fromArray([
  6963.                 $rdv->getId(),
  6964.                 $dateRdv->format('d/m/Y H:i'),
  6965.                 $joursEcoules ' jours',
  6966.                 $etat $etat->getLibelle() : 'Non défini',
  6967.                 $client $client->getName() . ' ' $client->getLastname() : '',
  6968.                 $client $client->getPhone() : '',
  6969.                 $client && $client->getClientStatus() ? $client->getClientStatus()->getLibelle() : 'Non défini',
  6970.                 $centre $centre->getName() : '',
  6971.                 $centre $centre->getPhone() : '',
  6972.                 $centre $centre->getAddress() . ', ' $centre->getPostale() . ' ' $centre->getCity() : '',
  6973.                 $rdv->getIdAudio() ? $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastname() : '',
  6974.             ], null'A' $row);
  6975.             $row++;
  6976.         }
  6977.         $writer = new Xlsx($spreadsheet);
  6978.         $filename "rdvs-$startDate-to-$endDate.xlsx";
  6979.         // Stream the file to browser
  6980.         $response = new \Symfony\Component\HttpFoundation\StreamedResponse(function () use ($writer) {
  6981.             $writer->save('php://output');
  6982.         });
  6983.         $dispositionHeader $response->headers->makeDisposition(
  6984.             \Symfony\Component\HttpFoundation\ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  6985.             $filename
  6986.         );
  6987.         $response->headers->set('Content-Type''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  6988.         $response->headers->set('Content-Disposition'$dispositionHeader);
  6989.         return $response;
  6990.     }
  6991.     /**
  6992.      * 
  6993.      * @Route("/admin/update-note", name="update_note", methods={"POST"})
  6994.      */
  6995.     public function updateNote(Request $requestEntityManagerInterface $em): JsonResponse
  6996.     {
  6997.         $data json_decode($request->getContent(), true);
  6998.         $id $data['id'] ?? null;
  6999.         $note $data['note'] ?? null;
  7000.         if (!$id || $note === null) {
  7001.             return new JsonResponse(['status' => 'error''message' => 'Invalid data'], 400);
  7002.         }
  7003.         $entity $em->getRepository(Rdv::class)->find($id);
  7004.         if (!$entity) {
  7005.             return new JsonResponse(['status' => 'error''message' => 'Entity not found'], 404);
  7006.         }
  7007.         $entity->setNote($note);
  7008.         $em->flush();
  7009.         return new JsonResponse(['status' => 'success']);
  7010.     }
  7011.     /**
  7012.      * 
  7013.      * @Route("/giuili-admin/edit-rdv/{rdvId}/centre/{centreId}", name="update_admin_rdv", methods={"GET"})
  7014.      */
  7015.     public function showRdvCentre(int $rdvIdCentre $centreId): Response
  7016.     {
  7017.         // dd("tets");
  7018.         $center $centres $this->getDoctrine()
  7019.             ->getRepository(AudioCentre::class)
  7020.             ->findOneBy(['id_centre' => $centreId->getId()]);
  7021.         $audio $center->getIdAudio();
  7022.         $motifs $this->getDoctrine()->getRepository(AudioMotif::class)
  7023.             ->findBy(['id_audio' => $audio'isDeleted' => 0]);
  7024.         return $this->render('easyadmin/rdv/centre_show.html.twig', [
  7025.             'audio' => $audio,
  7026.             'rdvId' => $rdvId,
  7027.             'centreId' => $centreId,
  7028.             'motifs' => $motifs,
  7029.         ]);
  7030.     }
  7031.     
  7032.     /**
  7033.      * 
  7034.      * @Route("/optical-center/edit-rdv/{rdvId}/centre/{centreId}", name="update_optical_rdv", methods={"GET"})
  7035.      */
  7036.     public function showRdvCentreOptical(int $rdvIdCentre $centreId): Response
  7037.     {
  7038.         // dd("tets");
  7039.         $center $centres $this->getDoctrine()
  7040.             ->getRepository(AudioCentre::class)
  7041.             ->findOneBy(['id_centre' => $centreId->getId()]);
  7042.         $audio $center->getIdAudio();
  7043.         $motifs $this->getDoctrine()->getRepository(AudioMotif::class)
  7044.             ->findBy(['id_audio' => $audio'isDeleted' => 0]);
  7045.         return $this->render('easyadmin/rdv/centre_show.html.twig', [
  7046.             'audio' => $audio,
  7047.             'rdvId' => $rdvId,
  7048.             'centreId' => $centreId,
  7049.             'motifs' => $motifs,
  7050.         ]);
  7051.     }
  7052.     /**
  7053.      * @Route("/update-rdv-easyadmin", name="update_rdv_easyadmin", methods={"POST"})
  7054.      */
  7055.     public function updateRdvEasyadmin(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendarRdvSmsService $rdvSms): Response
  7056.     {
  7057.         $data json_decode($request->getContent(), true);
  7058.         $rdv $this->getDoctrine()
  7059.             ->getRepository(Rdv::class)
  7060.             ->find($data["rdv_id"]);
  7061.         $pastDate $rdv->getDate();
  7062.         $entityManager $this->getDoctrine()->getManager();
  7063.         if (isset($data["etat_id"])) {
  7064.             $etat $this->getDoctrine()
  7065.                 ->getRepository(EtatRdv::class)
  7066.                 ->findOneBy(['id' => $data["etat_id"]]);
  7067.             if ($etat == null) {
  7068.                 return new Response(json_encode(([
  7069.                     'message' => 'Error, no etat found at this id',
  7070.                     'path' => 'src/Controller/TrustedUserController.php',
  7071.                     "status" => 400,
  7072.                 ])), 400);
  7073.             }
  7074.             $rdv->setIdEtat($etat);
  7075.         }
  7076.         if (isset($data["audio_id"])) {
  7077.             $audio $this->getDoctrine()
  7078.                 ->getRepository(Audio::class)
  7079.                 ->findOneBy(['id' => $data["audio_id"]]);
  7080.             if ($audio == null) {
  7081.                 return new Response(json_encode(([
  7082.                     'message' => 'Error, no audio found at this id',
  7083.                     'path' => 'src/Controller/TrustedUserController.php',
  7084.                     "status" => 400,
  7085.                 ])), 400);
  7086.             }
  7087.             $rdv->setIdAudio($audio);
  7088.         }
  7089.         if (isset($data["motif_id"])) {
  7090.             $motif $this->getDoctrine()
  7091.                 ->getRepository(Motif::class)
  7092.                 ->find($data["motif_id"]);
  7093.             if ($motif == null) {
  7094.                 return new Response(json_encode(([
  7095.                     'message' => 'Error, no motif found at this id',
  7096.                     'path' => 'src/Controller/TrustedUserController.php',
  7097.                     "status" => 400,
  7098.                 ])), 400);
  7099.             }
  7100.             $rdv->setIdMotif($motif);
  7101.         }
  7102.         if (isset($data["client_id"])) {
  7103.             $client $this->getDoctrine()
  7104.                 ->getRepository(Client::class)
  7105.                 ->findOneBy(['id' => $data["client_id"]]);
  7106.             if ($client == null) {
  7107.                 return new Response(json_encode(([
  7108.                     'message' => 'Error, no client found at this id',
  7109.                     'path' => 'src/Controller/TrustedUserController.php',
  7110.                     "status" => 400,
  7111.                 ])), 400);
  7112.             }
  7113.             $rdv->setIdClient($client);
  7114.         }
  7115.         if (isset($data["date"])) {
  7116.             $data["date"] = str_replace("h"":"$data["date"]);
  7117.             $date \DateTime::createFromFormat("Y-m-d\TH:i"$data["date"]);
  7118.             $audioMotif $this->getDoctrine()
  7119.                 ->getRepository(AudioMotif::class)
  7120.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  7121.             if ($audioMotif == null) {
  7122.                 return new Response(json_encode(([
  7123.                     'message' => 'Error, no motif of this id found at this audio',
  7124.                     'path' => 'src/Controller/RdvController.php',
  7125.                     "status" => 400,
  7126.                 ])), 400);
  7127.             }
  7128.             if ($rdv->getIdAudio()->getIsIndie()) {
  7129.                 if ($rdv->getIdCentre()) {
  7130.                     // regular centre audio indie
  7131.                     /** @var AudioCentre */
  7132.                     $liaison $this->getDoctrine()
  7133.                         ->getRepository(AudioCentre::class)
  7134.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  7135.                     if ($liaison == null) {
  7136.                         return new Response(json_encode(([
  7137.                             'message' => 'Error, audio isnt part of the centre',
  7138.                             'path' => 'src/Controller/RdvController.php',
  7139.                             "status" => 400,
  7140.                         ])), 400);
  7141.                     }
  7142.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  7143.                         return new Response(json_encode(([
  7144.                             'message' => 'Error, no horaire found for this audio',
  7145.                             'path' => 'src/Controller/RdvController.php',
  7146.                             "status" => 400,
  7147.                         ])), 400);
  7148.                     }
  7149.                 } else {
  7150.                     // lieu audio indie
  7151.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  7152.                         return new Response(json_encode(([
  7153.                             'message' => 'Error, no horaire found for this audio',
  7154.                             'path' => 'src/Controller/RdvController.php',
  7155.                             "status" => 400,
  7156.                         ])), 400);
  7157.                     }
  7158.                 }
  7159.             } else {
  7160.                 // regular centre
  7161.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  7162.                     return new Response(json_encode(([
  7163.                         'message' => 'Error, no horaire found for this audio',
  7164.                         'path' => 'src/Controller/RdvController.php',
  7165.                         "status" => 400,
  7166.                     ])), 400);
  7167.                 }
  7168.             }
  7169.             $rdv->setDate($date);
  7170.         }
  7171.         if (isset($data["comment"]) && $token->getIdClient()) {
  7172.             $rdv->setComment($data["comment"]);
  7173.         }
  7174.         if (isset($data["review"]) && $token->getIdClient()) {
  7175.             $rdv->setReview($data["review"]);
  7176.         }
  7177.         if (isset($data["note"])) {
  7178.             $rdv->setNote($data["note"]);
  7179.         }
  7180.         $entityManager->flush();
  7181.         $date $rdv->getDate();
  7182.         $smsDate $date->format('d-m-Y H:i');
  7183.         $oldDate $pastDate->format('d-m-Y H:i');
  7184.         $locale 'fr_FR';
  7185.         $formatter = new IntlDateFormatter(
  7186.             $locale,
  7187.             IntlDateFormatter::FULL,
  7188.             IntlDateFormatter::SHORT,
  7189.             null,
  7190.             IntlDateFormatter::GREGORIAN,
  7191.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  7192.         );
  7193.         $smsDateLongFormat $formatter->format($date);
  7194.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  7195.         $frenchDate ucfirst($frenchDate);
  7196.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  7197.         // notif client
  7198.         if ($rdv->getIdEtat()->getId() != 2) {
  7199.             $params = array(
  7200.                 "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  7201.                 "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  7202.                 "date" => $smsDateLongFormat,
  7203.                 "heure" => substr($smsDate1115),
  7204.                 "motif" => $rdv->getIdMotif()->getTitre(),
  7205.                 "centerName" => $rdv->getIdCentre()->getName(),
  7206.                 "centerAddress" => $rdv->getIdCentre()->getAddress(),
  7207.                 "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  7208.                 "audioMail" => $rdv->getIdAudio()->getMail(),
  7209.                 "centerPhone" => $rdv->getIdCentre()->getPhone(),
  7210.                 "centerCity" => $rdv->getIdCentre()->getCity(),
  7211.                 "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  7212.                 'titre' => 'Votre rendez-vous est modifié pour le',
  7213.                 'frenchDate' => $frenchDate,
  7214.             );
  7215.             $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  7216.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject184);
  7217.             $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.";
  7218.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  7219.         }
  7220.         //     //// == suppression
  7221.         else if ($rdv->getIdEtat()->getId() == 2) {
  7222.             $params = array(
  7223.                 "date" => substr($smsDate010),
  7224.                 "lien" => "{$_ENV['BASE_client']}search",
  7225.                 "heure" => substr($smsDate1115),
  7226.                 "patientName" => $client->getLastName(),
  7227.                 'titre' => 'Votre rendez-vous est annulé :',
  7228.                 'centerName' => $rdv->getIdCentre()->getName(),
  7229.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  7230.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  7231.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  7232.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  7233.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  7234.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  7235.                 'motif' => $rdv->getIdMotif()->getTitre(),
  7236.             );
  7237.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  7238.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject188);
  7239.             if ($data["sms"]) {
  7240.                 $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  7241.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  7242.             }
  7243.         }
  7244.         //notif Audio
  7245.         if ($rdv->getIdEtat()->getId() != 2) {
  7246.             $params = array(
  7247.                 "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  7248.                 "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  7249.                 "date" => substr($smsDate010),
  7250.                 "frenchDate" => $frenchDate,
  7251.                 "heure" => substr($smsDate1115),
  7252.                 'motif' => $rdv->getIdMotif()->getTitre(),
  7253.                 'clientPhone' => $client->getPhone(),
  7254.                 'clientNom' => $client->getLastname(),
  7255.                 'clientPrenom' => $client->getName(),
  7256.                 'clientCivilite' => $client->getCivilite(),
  7257.                 'clientPostal' => $client->getPostal(),
  7258.                 'clientMail' => $client->getMail(),
  7259.                 'centerName' => $rdv->getIdCentre()->getName(),
  7260.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  7261.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  7262.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  7263.                 'idPatient' => $client->getId(),
  7264.                 'proUrl' => "{$_ENV['BASE_logiciel']}",
  7265.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  7266.                 'titre' => 'Votre rendez-vous est modifié pour le :'
  7267.             );
  7268.             $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  7269.             $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  7270.             if ($rdv->getIdAudio()->getModifRdvMail()) {
  7271.                 $subject "🔀 Rendez-vous My Audio modifié du " $frenchDate " à " substr($smsDate1115);
  7272.                 $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject186);
  7273.             }
  7274.             if ($rdv->getIdAudio()->getModifRdvSms()) {
  7275.                 $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.";
  7276.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  7277.             }
  7278.         } else if ($rdv->getIdEtat()->getId() == 2) {
  7279.             $params = array(
  7280.                 "date" => substr($smsDate010),
  7281.                 "lien" => "{$_ENV['BASE_client']}search",
  7282.                 "heure" => substr($smsDate1115),
  7283.                 "patientName" => $client->getLastName(),
  7284.                 'titre' => 'Votre rendez-vous est annulé :',
  7285.                 'centerName' => $rdv->getIdCentre()->getName(),
  7286.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  7287.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  7288.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  7289.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  7290.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  7291.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  7292.                 'motif' => $rdv->getIdMotif()->getTitre(),
  7293.             );
  7294.             $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  7295.             $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  7296.             if ($rdv->getIdAudio()->getModifRdvMail()) {
  7297.                 $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  7298.                 $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject188);
  7299.             }
  7300.             if ($rdv->getIdAudio()->getModifRdvSms()) {
  7301.                 $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.";
  7302.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  7303.             }
  7304.         }
  7305.         /* generate sms notif on update */
  7306.         // update sms notification     
  7307.         $rdvSms->updateRdvSms($rdv);
  7308.         // google calendar update
  7309.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  7310.             ->findBy(array('audio' => $rdv->getIdAudio()));
  7311.         $data['rdv'] = $rdv->getId();
  7312.         $data['motif_id'] = $rdv->getIdMotif();
  7313.         $data['note'] = $rdv->getNote();
  7314.         if ($rdv->getIdClient() !== null) {
  7315.             $data["client_id"] = $rdv->getIdClient()->getId();
  7316.         }
  7317.         if ($rdv->getIdClientTemp() !== null) {
  7318.             $data["client_id_temp"] = $rdv->getIdClientTemp()->getId();
  7319.         }
  7320.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  7321.             ->findBy(array('rdv' => $rdv));
  7322.         foreach ($rdvEvents as $rdvEvent) {
  7323.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  7324.             $googleCalendar->updateEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
  7325.         }
  7326.         return new Response(json_encode(([
  7327.             "id" => $rdv->getId(),
  7328.             "motif_id" => $rdv->getIdMotif()->getId(),
  7329.             "audio_id" => $rdv->getIdAudio()->getId(),
  7330.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  7331.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  7332.             "fullName" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  7333.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  7334.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  7335.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  7336.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  7337.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  7338.             "centre_id" => $rdv->getIdCentre()->getId(),
  7339.             "centerName" => $rdv->getIdCentre()->getName(),
  7340.             "etat_id" => $rdv->getIdEtat()->getId(),
  7341.             "date" => $rdv->getDate(),
  7342.             "comment" => $rdv->getComment(),
  7343.             "note" => $rdv->getNote(),
  7344.             "review" => $rdv->getReview(),
  7345.             "status" => 200,
  7346.         ])));
  7347.     }
  7348.     private function checkRdvReminder($rdv): ?array
  7349.     {
  7350.         $dateRdv $rdv->getDate();
  7351.         $today = new \DateTime();
  7352.         $today->setTime(000);
  7353.         $dateRdv->setTime(000);
  7354.         $intervalDays $today->diff($dateRdv)->days;
  7355.         if ($intervalDays === 1) {
  7356.             $interval "24";
  7357.         } elseif ($intervalDays === 2) {
  7358.             $interval "48";
  7359.         } elseif ($intervalDays === 3) {
  7360.             $interval "72";
  7361.         } elseif ($intervalDays === 4) {
  7362.             $interval "96";
  7363.         } else { // >= 4 jours
  7364.             $interval "92";
  7365.         }
  7366.         $client $rdv->getIdClientTemp() ?: $rdv->getIdClient();
  7367.         $clientId $client $client->getId() : null;
  7368.         $clientName null;
  7369.         if ($client) {
  7370.             $clientName $client->getName() . ' ' $client->getLastName();
  7371.         }
  7372.         $motif $rdv->getIdMotif();
  7373.         $motifTitle $motif $motif->getTitre() : null;
  7374.         $centre $rdv->getIdCentre();
  7375.         $centreName null;
  7376.         if ($centre) {
  7377.             $centreName $centre->getName();
  7378.         }
  7379.         return [
  7380.             'rdvId' => $rdv->getId(),
  7381.             'clientId' => $clientId,
  7382.             'clientName' => $clientName ?? 'N/A',
  7383.             'interval' => $interval,
  7384.             'date' => $rdv->getDate() ? $rdv->getDate()->format('d-m-Y H:i') : null,
  7385.             'motif' => $motifTitle ?? 'N/A',
  7386.             'centreName' => $centreName ?? 'N/A',
  7387.         ];
  7388.     }
  7389. }