src/Controller/RdvController.php line 7136

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\EtatRdv;
  18. use App\Entity\LeadRdv;
  19. use App\Entity\Proches;
  20. use App\Entity\LieuTier;
  21. use App\Entity\RdvEvent;
  22. use App\Entity\AudioMotif;
  23. use App\Entity\CentreTier;
  24. use App\Entity\ClientTemp;
  25. use App\Entity\LeadStatus;
  26. use App\Entity\Remplacant;
  27. use App\Entity\TestClient;
  28. use App\Entity\AudioCentre;
  29. use App\Service\SmsHandler;
  30. use App\Entity\AccessCentre;
  31. use App\Entity\ClientStatus;
  32. use App\Entity\ClientBlocked;
  33. use App\Entity\CentreMutuelle;
  34. use App\Entity\LieuPrestation;
  35. use App\Entity\AudioSpecialite;
  36. use App\Service\PublicFunction;
  37. use App\Entity\CentrePrestation;
  38. use App\Entity\RegionDepartment;
  39. use App\Repository\RdvRepository;
  40. use Symfony\Component\Mime\Email;
  41. use App\Entity\Device\ClientDevice;
  42. use App\Entity\Notification\RdvSms;
  43. use App\Service\Lead\TwilioService;
  44. use App\Service\Lead\WhatsappService;
  45. use App\Entity\SynchronisationSetting;
  46. use App\Service\Lead\ElevenLabsService;
  47. use Doctrine\ORM\EntityManagerInterface;
  48. use Symfony\Contracts\Cache\ItemInterface;
  49. use App\Service\Cosium\ClientCosiumService;
  50. use App\Service\Notification\RdvSmsService;
  51. use Symfony\Contracts\Cache\CacheInterface;
  52. use App\Entity\Synchronisation\CosiumCenter;
  53. use Symfony\Component\Filesystem\Filesystem;
  54. use Symfony\Component\HttpFoundation\Request;
  55. use Symfony\Component\Mailer\MailerInterface;
  56. use Symfony\Component\HttpFoundation\Response;
  57. use Symfony\Component\Routing\Annotation\Route;
  58. use Doctrine\Common\Collections\ArrayCollection;
  59. use App\EasyAdmin\Controller\DashboardController;
  60. use Symfony\Component\HttpFoundation\JsonResponse;
  61. use App\EasyAdmin\Controller\LeadRdvCrudController;
  62. use App\Service\AdsCompany\RepresentativeCdaService;
  63. use App\Entity\Synchronisation\SynchronisationCosium;
  64. use App\Service\GoogleCalendar\GoogleCalendarService;
  65. use App\Service\Notification\EmailNotificationService;
  66. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  67. use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGenerator;
  68. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  69. class RdvController extends AbstractController
  70. {
  71.     private $emailNotificationService;
  72.     private $clientCosiumService;
  73.     private $rdvRepository;
  74.     private $entityManager;
  75.     private $cache;
  76.     private $twig;
  77.     private AdminUrlGenerator $adminUrlGenerator;
  78.     private WhatsappService $whatsapp;
  79.     public function __construct(CacheInterface $cacheEntityManagerInterface $entityManagerEmailNotificationService $emailNotificationServiceClientCosiumService $clientCosiumServiceRdvRepository $rdvRepositoryEnvironment $twigAdminUrlGenerator $adminUrlGeneratorWhatsappService $whatsapp)
  80.     {
  81.         $this->entityManager $entityManager;
  82.         $this->emailNotificationService $emailNotificationService;
  83.         $this->clientCosiumService $clientCosiumService;
  84.         $this->rdvRepository $rdvRepository;
  85.         $this->cache $cache;
  86.         $this->twig $twig;
  87.         $this->adminUrlGenerator $adminUrlGenerator;
  88.         $this->whatsapp $whatsapp;
  89.     }
  90.     /**
  91.      * @Route("/rdv/{id}", name="deleteRdvByID", methods={"DELETE"})
  92.      */
  93.     public function deleteRdvByID(Request $requestRdv $rdvGoogleCalendarService $googleCalendar)
  94.     {
  95.         if (!$request->query->get('token')) {
  96.             return new Response(json_encode([
  97.                 "message" => "Pas de token n'a été spécifié",
  98.                 "status" => 401,
  99.             ]), 401);
  100.         }
  101.         $entityManager $this->getDoctrine()->getManager();
  102.         /** @var Token */
  103.         $token $this->getDoctrine()
  104.             ->getRepository(Token::class)
  105.             ->findOneBy(['token' => $request->query->get('token')]);
  106.         if (!$token) {
  107.             return new Response(json_encode([
  108.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  109.                 "status" => 404,
  110.             ]), 404);
  111.         }
  112.         // get token age
  113.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  114.         // if the token if older than 7 days
  115.         if ($dateDiff->7) {
  116.             $entityManager->remove($token);
  117.             $entityManager->flush();
  118.             return $this->json([
  119.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  120.                 'path' => 'src/Controller/ClientController.php',
  121.                 "status" => 401,
  122.             ], 401);
  123.         }
  124.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  125.             return new Response(json_encode([
  126.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  127.                 "status" => 404,
  128.             ]), 404);
  129.         }
  130.         $entityManager->remove($rdv);
  131.         $entityManager->flush();
  132.         return new Response(json_encode(([
  133.             'message' => "Rdv has been successfully deleted",
  134.             "status" => 200,
  135.         ])));
  136.     }
  137.     /**
  138.      * @Route("/rdv/{id}", name="getRdvByID", methods={"GET","HEAD"})
  139.      */
  140.     public function getRdvByID(Request $requestRdv $rdvPublicFunction $publicFunction)
  141.     {
  142.         if (!$request->query->get('token')) {
  143.             return new Response(json_encode([
  144.                 "message" => "Pas de token n'a été spécifié",
  145.                 "status" => 401,
  146.             ]), 401);
  147.         }
  148.         $entityManager $this->getDoctrine()->getManager();
  149.         /** @var Token */
  150.         $token $this->getDoctrine()
  151.             ->getRepository(Token::class)
  152.             ->findOneBy(['token' => $request->query->get('token')]);
  153.         if (!$token) {
  154.             return new Response(json_encode([
  155.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  156.                 "status" => 404,
  157.             ]), 404);
  158.         }
  159.         // get token age
  160.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  161.         // if the token if older than 7 days
  162.         if ($dateDiff->7) {
  163.             $entityManager->remove($token);
  164.             $entityManager->flush();
  165.             return $this->json([
  166.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  167.                 'path' => 'src/Controller/ClientController.php',
  168.                 "status" => 401,
  169.             ], 401);
  170.         }
  171.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  172.             return new Response(json_encode([
  173.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  174.                 "status" => 404,
  175.             ]), 404);
  176.         }
  177.         /** @var AudioCentre */
  178.         $liaison $this->getDoctrine()->getRepository(AudioCentre::class)
  179.             ->findOneBy(array('id_audio' => $rdv->getIdAudio(), 'id_centre' => $rdv->getIdCentre(), 'isConfirmed' => true));
  180.         // Motif filter
  181.         /** @var AudioMotif[] */
  182.         $motifs $this->getDoctrine()->getRepository(AudioMotif::class)
  183.             ->findBy(array('id_audio' => $rdv->getIdAudio(), 'id_motif' => $rdv->getIdMotif()));
  184.         $resultMotif = new ArrayCollection();
  185.         foreach ($motifs as $motif) {
  186.             $resultMotif->add([
  187.                 "id" => $motif->getIdMotif()->getId(),
  188.                 "titre" => $motif->getIdMotif()->getTitre(),
  189.                 "consigne" => $motif->getConsigne(),
  190.                 "duration" => $motif->getDuration(),
  191.             ]);
  192.         }
  193.         // Specialities
  194.         /** @var AudioSpecialite[] */
  195.         $specialities $this->getDoctrine()->getRepository(AudioSpecialite::class)
  196.             ->findBy(array('id_audio' => $rdv->getIdAudio()));
  197.         $resultSpeciality = new ArrayCollection();
  198.         foreach ($specialities as $speciality) {
  199.             $resultSpeciality->add([
  200.                 "id" => $speciality->getIdSpecialite()->getId(),
  201.                 "titre" => $speciality->getIdSpecialite()->getLibelle(),
  202.             ]);
  203.         }
  204.         if ($rdv->getIdCentre())
  205.         /** @var AccessCentre*/
  206.         {
  207.             $accessCentre $this->getDoctrine()->getRepository(AccessCentre::class)
  208.                 ->findOneBy(array('id_centre' => $rdv->getIdCentre()));
  209.         } else
  210.         /** @var AccessCentre*/
  211.         {
  212.             $accessCentre $this->getDoctrine()->getRepository(AccessCentre::class)
  213.                 ->findOneBy(array('id_lieu' => $rdv->getIdLieu()));
  214.         }
  215.         if ($rdv->getIdCentre())
  216.         /** @var CentrePrestation[]*/
  217.         {
  218.             $prestations $this->getDoctrine()->getRepository(CentrePrestation::class)
  219.                 ->findBy(array('id_centre' => $liaison->getIdCentre()->getId()));
  220.         } else
  221.         /** @var LieuPrestation[]*/
  222.         {
  223.             $prestations $this->getDoctrine()->getRepository(LieuPrestation::class)
  224.                 ->findBy(array('id_lieu' => $rdv->getIdLieu()));
  225.         }
  226.         $resultPrestation = new ArrayCollection();
  227.         foreach ($prestations as $prestation) {
  228.             $resultPrestation->add([
  229.                 "id" => $prestation->getIdPrestation()->getId(),
  230.                 "titre" => $prestation->getIdPrestation()->getLibelle(),
  231.             ]);
  232.         }
  233.         $mutuelles $this->getDoctrine()->getRepository(CentreMutuelle::class)
  234.             ->findBy(array('id_centre' => $rdv->getIdCentre()));
  235.         $resultMutuelle = new ArrayCollection();
  236.         foreach ($mutuelles as $mutuelle) {
  237.             $resultMutuelle->add([
  238.                 "id" => $mutuelle->getIdMutuelle()->getId(),
  239.                 "titre" => $mutuelle->getIdMutuelle()->getLibelle(),
  240.             ]);
  241.         }
  242.         if ($rdv->getIdCentre())
  243.         /** @var CentreTier[]*/
  244.         {
  245.             $tiers $this->getDoctrine()->getRepository(CentreTier::class)
  246.                 ->findBy(array('id_centre' => $liaison->getIdCentre()->getId()));
  247.         } else
  248.         /** @var LieuTier[]*/
  249.         {
  250.             $tiers $this->getDoctrine()->getRepository(LieuTier::class)
  251.                 ->findBy(array('id_lieu' => $rdv->getIdLieu()));
  252.         }
  253.         $resultTier = new ArrayCollection();
  254.         foreach ($tiers as $tier) {
  255.             $resultTier->add([
  256.                 "id" => $tier->getIdTier()->getId(),
  257.                 "titre" => $tier->getIdTier()->getLibelle(),
  258.             ]);
  259.         }
  260.         $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  261.         /** @var Rdv[] */
  262.         $audioRdvs $this->getDoctrine()->getRepository(Rdv::class)
  263.             ->findAllReviewsAudio($rdv->getIdAudio()->getId());
  264.         /** @var Rdv[] */
  265.         $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  266.             ->findAllReviewsCentre($rdvCentre->getId());
  267.         // Comment
  268.         /** @var Rdv[] */
  269.         $rdvs $this->getDoctrine()->getRepository(Rdv::class)
  270.             ->findBy(array('id_audio' => $rdv->getIdAudio()));
  271.         $comments = [];
  272.         foreach ($rdvs as $rdv)
  273.             if ($rdv->getComment() && $rdv->getReview() && $rdv->getIdClient())
  274.                 array_push($comments, [
  275.                     "id" => $rdv->getIdClient()->getId(),
  276.                     "name" => $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname()[0] . ".",
  277.                     "comment" => $rdv->getComment(),
  278.                     "isMale" => $rdv->getIdClient()->getCivilite() == "Monsieur",
  279.                     "review" => $rdv->getReview(),
  280.                 ]);
  281.         return new Response(json_encode(([
  282.             "id" => $rdv->getId(),
  283.             "motif_id" => $rdv->getIdMotif()->getId(),
  284.             "motif_titre" => $rdv->getIdMotif()->getTitre(),
  285.             "audio_id" => $rdv->getIdAudio()->getId(),
  286.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  287.             "client_id" => $rdv->getIdClient()->getId(),
  288.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  289.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  290.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  291.             "etat_id" => $rdv->getIdEtat()->getId(),
  292.             "date" => $rdv->getDate(),
  293.             "comment" => $rdv->getComment(),
  294.             "review" => $rdv->getReview(),
  295.             "note" => $rdv->getNote(),
  296.             "testclient" => $rdv->getTestClient() ? [
  297.                 "result" => $rdv->getTestClient()->getResultTonal(),
  298.                 "date" => $rdv->getTestClient()->getDate(),
  299.                 "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  300.             ] : null,
  301.             "comments" => $comments,
  302.             "audio" => [
  303.                 "id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : $rdv->getIdAudio()->getId(),
  304.                 "civilite" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getCivilite() : $rdv->getIdAudio()->getCivilite(),
  305.                 "name" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getName() : $rdv->getIdAudio()->getName(),
  306.                 "lastname" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getLastname() : $rdv->getIdAudio()->getLastname(),
  307.                 "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  308.                 "mail" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getMail() : $rdv->getIdAudio()->getMail(),
  309.                 "phone" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getPhone() : $rdv->getIdAudio()->getPhone(),
  310.                 "adeli" => $rdv->getIdAudio()->getAdeli(),
  311.                 "pin" => $rdv->getIdAudio()->getPin(),
  312.                 "description" => $rdv->getIdAudio()->getDescription(),
  313.                 "averageRating" => $publicFunction->calculateRating($audioRdvs),
  314.                 "nbrReview" => count($audioRdvs),
  315.                 "motifs" => $resultMotif->toArray(),
  316.                 "specialities" => $resultSpeciality->toArray(),
  317.             ],
  318.             "centre" => [
  319.                 "id" => $rdvCentre->getId(),
  320.                 "audio_id" => $rdvCentre->getIdGerant()->getId(),
  321.                 "name" => $rdvCentre->getName(),
  322.                 "imgUrl" => $rdvCentre->getImgUrl(),
  323.                 "isRdvDomicile" => $rdv->getIdCentre() ? $rdvCentre->getIsRdvDomicile() : $rdv->getIdAudio()->getIsRdvDomicileIndie(),
  324.                 "address" => $rdvCentre->getAddress(),
  325.                 "postale" => $rdvCentre->getPostale(),
  326.                 "city" => $rdvCentre->getCity(),
  327.                 "finess" => $rdvCentre->getFiness(),
  328.                 "siret" => $rdvCentre->getSiret(),
  329.                 "website" => $rdvCentre->getWebsite(),
  330.                 "phone" => $rdvCentre->getPhone(),
  331.                 "isHandicap" => $rdvCentre->getIsHandicap(),
  332.                 "longitude" => $rdvCentre->getLongitude(),
  333.                 "latitude" => $rdvCentre->getLatitude(),
  334.                 "averageRating" => $publicFunction->calculateRating($centreRdvs),
  335.                 "nbrReview" => count($centreRdvs),
  336.                 "tram" => $accessCentre->getTram(),
  337.                 "rer" => $accessCentre->getRer(),
  338.                 "metro" => $accessCentre->getMetro(),
  339.                 "bus" => $accessCentre->getBus(),
  340.                 "parking" => $accessCentre->getParkingPublic(),
  341.                 "description" => $rdv->getIdCentre()->getDescription(),
  342.                 "parkingPrivate" => $accessCentre->getParkingPrivate(),
  343.                 "other" => $accessCentre->getOther(),
  344.                 "prestations" => $resultPrestation->toArray(),
  345.                 "mutuelles" => $resultMutuelle->toArray(),
  346.                 "tiers" => $resultTier->toArray(),
  347.                 "isLieu" => false,
  348.                 "schedule" => $rdv->getIdAudio()->getIsIndie() == false $rdv->getIdCentre()->getHoraire() : ($rdv->getIdLieu() ? $rdv->getIdLieu()->getHoraire() : $liaison->getHoraire()),
  349.             ],
  350.             "status" => 200,
  351.         ])));
  352.     }
  353.     /**
  354.      * @Route("/rdvs/client/{id}", name="getRdvsByClientID", methods={"GET","HEAD"})
  355.      */
  356.     public function getRdvsByClientID(Request $requestClient $clientPublicFunction $publicFunction)
  357.     {
  358.         if (!$request->query->get('token')) {
  359.             return new Response(json_encode([
  360.                 "message" => "Pas de token n'a été spécifié",
  361.                 "status" => 401,
  362.             ]), 401);
  363.         }
  364.         $entityManager $this->getDoctrine()->getManager();
  365.         /** @var Token */
  366.         $token $this->getDoctrine()
  367.             ->getRepository(Token::class)
  368.             ->findOneBy(['token' => $request->query->get('token')]);
  369.         if (!$token) {
  370.             return new Response(json_encode([
  371.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  372.                 "status" => 404,
  373.             ]), 404);
  374.         }
  375.         // get token age
  376.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  377.         // if the token if older than 7 days
  378.         if ($dateDiff->7) {
  379.             $entityManager->remove($token);
  380.             $entityManager->flush();
  381.             return $this->json([
  382.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  383.                 'path' => 'src/Controller/ClientController.php',
  384.                 "status" => 401,
  385.             ], 401);
  386.         }
  387.         if ($token->getIdClient()) {
  388.             if ($client != $token->getIdClient()) {
  389.                 return new Response(json_encode([
  390.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  391.                     "status" => 404,
  392.                 ]), 404);
  393.             }
  394.         } else if ($token->getIdAudio()) {
  395.             /** @var Token */
  396.             $token $this->getDoctrine()
  397.                 ->getRepository(Rdv::class)
  398.                 ->findOneBy(['id_client' => $client'id_audio' => $token->getIdAudio()]);
  399.             if ($client != $token->getIdClient()) {
  400.                 return new Response(json_encode([
  401.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  402.                     "status" => 404,
  403.                 ]), 404);
  404.             }
  405.         } else {
  406.             return new Response(json_encode([
  407.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  408.                 "status" => 404,
  409.             ]), 404);
  410.         }
  411.         if ($request->query->get('audio')) {
  412.             /** @var Rdv[] */
  413.             $rdvs $this->getDoctrine()
  414.                 ->getRepository(Rdv::class)
  415.                 ->findBy(['id_client' => $client->getId(), 'id_audio' => $token->getIdAudio()]);
  416.             $rdvResult = new ArrayCollection();
  417.         } else {
  418.             /** @var Rdv[] */
  419.             $rdvs $this->getDoctrine()
  420.                 ->getRepository(Rdv::class)
  421.                 ->findBy(['id_client' => $client->getId()]);
  422.             $rdvResult = new ArrayCollection();
  423.         }
  424.         if ($request->query->get('old')) {
  425.             $oldRdvResult = new ArrayCollection();
  426.         }
  427.         foreach ($rdvs as $rdv) {
  428.             if ($rdv->getIdEtat()->getId() != 1) {
  429.                 continue;
  430.             }
  431.             /** @var AudioMotif */
  432.             $audioMotif $this->getDoctrine()
  433.                 ->getRepository(AudioMotif::class)
  434.                 ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  435.             if (!$audioMotif) {
  436.                 continue;
  437.             }
  438.             $duration '';
  439.             if (is_null($rdv->getDuration())) {
  440.                 $duration $audioMotif->getDuration();
  441.             } else {
  442.                 $duration $rdv->getDuration();
  443.             }
  444.             $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  445.             /** @var Rdv[] */
  446.             $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  447.                 ->findAllReviewsCentre($rdvCentre->getId());
  448.             $rdvItem = [
  449.                 "id" => $rdv->getId(),
  450.                 "motif_id" => $rdv->getIdMotif()->getId(),
  451.                 "duration" => $duration,
  452.                 "color" => $audioMotif->getColor(),
  453.                 "audio_id" => $rdv->getIdAudio()->getId(),
  454.                 "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  455.                 "audio_name" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getName() . " " $rdv->getRemplacant()->getLastname() : $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  456.                 "client_id" => $rdv->getIdClient()->getId(),
  457.                 "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() . " " $rdv->getIdProche()->getLastname() : $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname(),
  458.                 "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  459.                 "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  460.                 "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  461.                 "testclient" => $rdv->getTestClient() ? [
  462.                     "result" => $rdv->getTestClient()->getResultTonal(),
  463.                     "date" => $rdv->getTestClient()->getDate(),
  464.                     "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  465.                 ] : null,
  466.                 "name" => $rdvCentre->getName(),
  467.                 "phone" => $rdvCentre->getPhone(),
  468.                 "imgUrl" => $rdvCentre->getImgUrl(),
  469.                 "address" => $rdvCentre->getAddress(),
  470.                 "postale" => $rdvCentre->getPostale(),
  471.                 "city" => $rdvCentre->getCity(),
  472.                 "etat_id" => $rdvCentre->getId(),
  473.                 "averageRating" => $publicFunction->calculateRating($centreRdvs),
  474.                 "nbrReview" => count($centreRdvs),
  475.                 "acceptedCurrency" => "CB Chèque",
  476.                 "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  477.                 "note" => $rdv->getNote(),
  478.                 "comment" => $rdv->getComment(),
  479.                 "review" => $rdv->getReview(),
  480.             ];
  481.             if ($rdv->getDate() >= new DateTime()) {
  482.                 $rdvResult->add($rdvItem);
  483.             } else if ($request->query->get('old')) {
  484.                 $oldRdvResult->add($rdvItem);
  485.             }
  486.         }
  487.         if ($request->query->get('old')) {
  488.             if ($request->query->get('onlyOld')) {
  489.                 if (count($rdvResult) > || count($oldRdvResult) > 0) {
  490.                     return new Response(json_encode(([
  491.                         "oldRdv" => $oldRdvResult->toArray(),
  492.                         "status" => 200,
  493.                     ])));
  494.                 } else {
  495.                     return new Response(json_encode(([
  496.                         "message" => "Aucun rendez-vous n'a été trouvé!",
  497.                         "test" => "count:" count($rdvs),
  498.                         'path' => 'src/Controller/RdvController.php',
  499.                         "rdv" => array(),
  500.                         "oldRdv" => array(),
  501.                         "status" => 404,
  502.                     ])));
  503.                 }
  504.             } else {
  505.                 if (count($rdvResult) > || count($oldRdvResult) > 0) {
  506.                     return new Response(json_encode(([
  507.                         "rdv" => $rdvResult->toArray(),
  508.                         "oldRdv" => $oldRdvResult->toArray(),
  509.                         "status" => 200,
  510.                     ])));
  511.                 } else {
  512.                     return new Response(json_encode(([
  513.                         "message" => "Aucun rendez-vous n'a été trouvé!",
  514.                         "test" => "count:" count($rdvs),
  515.                         'path' => 'src/Controller/RdvController.php',
  516.                         "rdv" => array(),
  517.                         "oldRdv" => array(),
  518.                         "status" => 404,
  519.                     ])));
  520.                 }
  521.             }
  522.         } else {
  523.             if (count($rdvResult) > 0) {
  524.                 return new Response(json_encode(([
  525.                     "content" => $rdvResult->toArray(),
  526.                     "status" => 200,
  527.                 ])));
  528.             } else {
  529.                 return new Response(json_encode(([
  530.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  531.                     "test" => "count2:" count($rdvs),
  532.                     'path' => 'src/Controller/RdvController.php',
  533.                     "status" => 404,
  534.                 ])));
  535.             }
  536.         }
  537.     }
  538.     /**
  539.      * @Route("/rdvs/client/{id}/centre", name="getRdvsByClientIDForCentre", methods={"GET","HEAD"})
  540.      */
  541.     public function getRdvsByClientIDForCentre(Request $requestClient $clientPublicFunction $publicFunction)
  542.     {
  543.         if (!$request->query->get('token')) {
  544.             return new Response(json_encode([
  545.                 "message" => "Pas de token n'a été spécifié",
  546.                 "status" => 401,
  547.             ]), 401);
  548.         }
  549.         $entityManager $this->getDoctrine()->getManager();
  550.         /** @var Token */
  551.         $token $this->getDoctrine()
  552.             ->getRepository(Token::class)
  553.             ->findOneBy(['token' => $request->query->get('token')]);
  554.         if (!$token) {
  555.             return new Response(json_encode([
  556.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  557.                 "status" => 404,
  558.             ]), 404);
  559.         }
  560.         $audio $this->getDoctrine()
  561.             ->getRepository(Audio::class)
  562.             ->findOneBy(['id' => $request->query->get('audio')]);
  563.         $audioCentre $this->getDoctrine()
  564.             ->getRepository(AudioCentre::class)
  565.             ->findOneBy(['id_audio' => $audio]);
  566.         // get token age
  567.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  568.         // if the token if older than 7 days
  569.         if ($dateDiff->7) {
  570.             $entityManager->remove($token);
  571.             $entityManager->flush();
  572.             return $this->json([
  573.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  574.                 'path' => 'src/Controller/ClientController.php',
  575.                 "status" => 401,
  576.             ], 401);
  577.         }
  578.         if ($token->getIdClient()) {
  579.             if ($client != $token->getIdClient()) {
  580.                 return new Response(json_encode([
  581.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  582.                     "status" => 404,
  583.                 ]), 404);
  584.             }
  585.         } else if ($token->getIdAudio()) {
  586.             /** @var Token */
  587.             if ($token->getIdAudio() != $audio) {
  588.                 return new Response(json_encode([
  589.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  590.                     "status" => 404,
  591.                 ]), 404);
  592.             }
  593.         } else {
  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.         if ($request->query->get('centre')) {
  600.             /** @var Rdv[] */
  601.             $rdvs $this->getDoctrine()
  602.                 ->getRepository(Rdv::class)
  603.                 ->findBy(['id_client' => $client->getId(), 'id_centre' => $audioCentre->getIdCentre()]);
  604.             $rdvResult = new ArrayCollection();
  605.         } else {
  606.             /** @var Rdv[] */
  607.             $rdvs $this->getDoctrine()
  608.                 ->getRepository(Rdv::class)
  609.                 ->findBy(['id_client' => $client->getId()]);
  610.             $rdvResult = new ArrayCollection();
  611.         }
  612.         if ($request->query->get('old')) {
  613.             $oldRdvResult = new ArrayCollection();
  614.         }
  615.         foreach ($rdvs as $rdv) {
  616.             /*if ($rdv->getIdEtat()->getId() != 1) {
  617.                 continue;
  618.             }*/
  619.             /** @var AudioMotif */
  620.             $audioMotif $this->getDoctrine()
  621.                 ->getRepository(AudioMotif::class)
  622.                 ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  623.             if (!$audioMotif) {
  624.                 continue;
  625.             }
  626.             $duration '';
  627.             if (is_null($rdv->getDuration())) {
  628.                 $duration $audioMotif->getDuration();
  629.             } else {
  630.                 $duration $rdv->getDuration();
  631.             }
  632.             $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  633.             /** @var Rdv[] */
  634.             $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  635.                 ->findAllReviewsCentre($rdvCentre->getId());
  636.             $rdvItem = [
  637.                 "id" => $rdv->getId(),
  638.                 "motif_id" => $rdv->getIdMotif()->getId(),
  639.                 "duration" => $duration,
  640.                 "color" => $audioMotif->getColor(),
  641.                 "audio_id" => $rdv->getIdAudio()->getId(),
  642.                 "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  643.                 "audio_name" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getName() . " " $rdv->getRemplacant()->getLastname() : $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  644.                 "client_id" => $rdv->getIdClient()->getId(),
  645.                 "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() . " " $rdv->getIdProche()->getLastname() : $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname(),
  646.                 "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  647.                 "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  648.                 "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  649.                 "testclient" => $rdv->getTestClient() ? [
  650.                     "result" => $rdv->getTestClient()->getResultTonal(),
  651.                     "date" => $rdv->getTestClient()->getDate(),
  652.                     "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  653.                 ] : null,
  654.                 "name" => $rdvCentre->getName(),
  655.                 "phone" => $rdvCentre->getPhone(),
  656.                 "imgUrl" => $rdvCentre->getImgUrl(),
  657.                 "address" => $rdvCentre->getAddress(),
  658.                 "postale" => $rdvCentre->getPostale(),
  659.                 "city" => $rdvCentre->getCity(),
  660.                 "etat_id" => $rdvCentre->getId(),
  661.                 "averageRating" => $publicFunction->calculateRating($centreRdvs),
  662.                 "nbrReview" => count($centreRdvs),
  663.                 "acceptedCurrency" => "CB Chèque",
  664.                 "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  665.                 "note" => $rdv->getNote(),
  666.                 "comment" => $rdv->getComment(),
  667.                 "review" => $rdv->getReview(),
  668.                 "status" => $rdv->getIdEtat()->getLibelle()
  669.             ];
  670.             // dd(new DateTime());
  671.             if ($rdv->getDate() >= new DateTime()) {
  672.                 $rdvResult->add($rdvItem);
  673.             } else if ($request->query->get('old')) {
  674.                 $oldRdvResult->add($rdvItem);
  675.             }
  676.         }
  677.         if ($request->query->get('old')) {
  678.             if (count($rdvResult) > || count($oldRdvResult) > 0) {
  679.                 return new Response(json_encode(([
  680.                     "rdv" => $rdvResult->toArray(),
  681.                     "oldRdv" => $oldRdvResult->toArray(),
  682.                     "status" => 200,
  683.                 ])));
  684.             } else {
  685.                 return new Response(json_encode(([
  686.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  687.                     "test" => "count:" count($rdvs),
  688.                     'path' => 'src/Controller/RdvController.php',
  689.                     "status" => 404,
  690.                 ])), 404);
  691.             }
  692.         } else {
  693.             if (count($rdvResult) > 0) {
  694.                 return new Response(json_encode(([
  695.                     "content" => $rdvResult->toArray(),
  696.                     "status" => 200,
  697.                 ])));
  698.             } else {
  699.                 return new Response(json_encode(([
  700.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  701.                     "test" => "count2:" count($rdvs),
  702.                     'path' => 'src/Controller/RdvController.php',
  703.                     "status" => 404,
  704.                 ])));
  705.             }
  706.         }
  707.     }
  708.     /////// CRON
  709.     /**
  710.      * @Route("/confirmRdvSms", name="confirmRdvSms", methods={"GET","HEAD"})
  711.      */
  712.     public function confirmRdvSms(PublicFunction $publicFunction): Response
  713.     {
  714.         $date = new DateTime();
  715.         $minutes_to_add 30;
  716.         $date->add(new DateInterval('PT' $minutes_to_add 'M'));
  717.         $date->setTimezone(new DateTimeZone('Europe/Paris'));
  718.         $currentDate $date->format('Y-m-d H:i:00');
  719.         $toSend $this->getDoctrine()->getRepository(Rdv::class)
  720.             ->findRdvsIn10Mins($currentDate);
  721.         $entityManager $this->getDoctrine()->getManager();
  722.         $rdvResult = new ArrayCollection();
  723.         foreach ($toSend as $rdv) {
  724.             $date $rdv->getDate();
  725.             // $smsDate = $date->format('d-m-Y H:i');
  726.             //$client = $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  727.             //$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.";
  728.             // // $publicFunction->sendEmail("MyAudio <noreply@myaudio.fr>", $client->getMail(), "My Audio: Testing CRON", "<p>Testing Cron.</p>");
  729.             //$response = $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $client->getPhone(), 4);
  730.             //$another_response = explode(" | ", $response);
  731.             // $idSms = trim($another_response[2]);
  732.             // $rdv->setIdSms($idSms);
  733.             //$entityManager->persist($rdv);
  734.             // $entityManager->flush();
  735.         }
  736.         return new Response(json_encode([
  737.             // "test" => $idSms,
  738.             "currentDate" => $currentDate
  739.         ]));
  740.     }
  741.     /////// CRON 
  742.     /**
  743.      * @Route("/validateRdvSms", name="validateRdvSms", methods={"GET","HEAD"})
  744.      */
  745.     public function validateRdvSms(Request $requestPublicFunction $publicFunction): Response
  746.     {
  747.         $smsId $request->query->get('token');
  748.         $message $request->query->get('message');
  749.         $rdv $this->getDoctrine()
  750.             ->getRepository(Rdv::class)
  751.             ->findOneBy(['id_sms' => $smsId]);
  752.         $date $rdv->getDate();
  753.         $currentDate date('Y-m-d H:i:s');
  754.         $smsDate $date->format('d-m-Y H:i');
  755.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  756.         $entityManager $this->getDoctrine()->getManager();
  757.         if ($date $currentDate) {
  758.             if ($message == "1") {
  759.                 $sms "Parfait, votre audioprothésiste est averti de votre venue. Présentez-vous à l'accueil du centre, il vous recevra dans quelques minutes.\nNe pas répondre";
  760.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  761.             } else if ($message == "2") {
  762.                 $sms "Votre absence est bien enregistrée, votre audioprothésiste est averti. Contactez votre centre pour reprogrammer un autre RDV.\nNe pas répondre.";
  763.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  764.                 $etat $this->getDoctrine()
  765.                     ->getRepository(EtatRdv::class)
  766.                     ->findOneBy(['id' => 2]);
  767.                 $rdv->setIdEtat($etat);
  768.                 $entityManager->persist($rdv);
  769.                 $entityManager->flush();
  770.             } else {
  771.                 return new Response(json_encode([
  772.                     "message" => "La réponse spécifiée est incorrecte",
  773.                     "status" => 401,
  774.                 ]), 401);
  775.             }
  776.         } else {
  777.             return new Response(json_encode([
  778.                 "message" => "Le rendez-vous est déjà passé, vous ne pouvez plus répondre à ce sms !",
  779.                 "status" => 401,
  780.             ]), 401);
  781.         }
  782.         return new Response(json_encode([
  783.             "smsId" => $smsId,
  784.             "message" => $currentDate
  785.         ]));
  786.     }
  787.     /**
  788.      * @Route("/rdvs/old/client/{id}", name="getOldRdvsByClientId", methods={"GET","HEAD"})
  789.      */
  790.     public function getOldRdvsByClientId(Request $requestClient $clientPublicFunction $publicFunction)
  791.     {
  792.         if (!$request->query->get('token')) {
  793.             return new Response(json_encode([
  794.                 "message" => "Pas de token n'a été spécifié",
  795.                 "status" => 401,
  796.             ]), 401);
  797.         }
  798.         $entityManager $this->getDoctrine()->getManager();
  799.         /** @var Token */
  800.         $token $this->getDoctrine()
  801.             ->getRepository(Token::class)
  802.             ->findOneBy(['token' => $request->query->get('token')]);
  803.         if (!$token) {
  804.             return new Response(json_encode([
  805.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  806.                 "status" => 404,
  807.             ]), 404);
  808.         }
  809.         // get token age
  810.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  811.         // if the token if older than 7 days
  812.         if ($dateDiff->7) {
  813.             $entityManager->remove($token);
  814.             $entityManager->flush();
  815.             return $this->json([
  816.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  817.                 'path' => 'src/Controller/ClientController.php',
  818.                 "status" => 401,
  819.             ], 401);
  820.         }
  821.         if ($token->getIdClient()) {
  822.             if ($client != $token->getIdClient()) {
  823.                 return new Response(json_encode([
  824.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  825.                     "status" => 404,
  826.                 ]), 404);
  827.             }
  828.         } else if ($token->getIdAudio()) {
  829.             /** @var Token */
  830.             $token $this->getDoctrine()
  831.                 ->getRepository(Rdv::class)
  832.                 ->findOneBy(['id_client' => $client'id_audio' => $token->getIdAudio()]);
  833.             if ($client != $token->getIdClient()) {
  834.                 return new Response(json_encode([
  835.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  836.                     "status" => 404,
  837.                 ]), 404);
  838.             }
  839.         } else {
  840.             return new Response(json_encode([
  841.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  842.                 "status" => 404,
  843.             ]), 404);
  844.         }
  845.         if ($request->query->get('audio')) {
  846.             /** @var ActivityRepository */
  847.             $activityRepo $this->getDoctrine();
  848.             if ($request->query->get('limit')) {
  849.                 /** @var Rdv[] */
  850.                 $rdvs $activityRepo
  851.                     ->getRepository(Rdv::class)
  852.                     ->findLastsOldRdvsWithLimit($request->query->get('limit'), $client->getId(), $request->query->get('audio'), new DateTime());
  853.                 $rdvResult = new ArrayCollection();
  854.             } else {
  855.                 /** @var Rdv[] */
  856.                 $rdvs $activityRepo
  857.                     ->getRepository(Rdv::class)
  858.                     ->findOldRdvs($client->getId(), $request->query->get('audio'), new DateTime());
  859.                 $rdvResult = new ArrayCollection();
  860.             }
  861.             foreach ($rdvs as $rdv) {
  862.                 /*if ($rdv->getIdEtat()->getId() != 1) {
  863.                     continue;
  864.                 }*/
  865.                 /** @var AudioMotif */
  866.                 $audioMotif $this->getDoctrine()
  867.                     ->getRepository(AudioMotif::class)
  868.                     ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  869.                 if (!$audioMotif) {
  870.                     continue;
  871.                 }
  872.                 $duration '';
  873.                 if (is_null($rdv->getDuration())) {
  874.                     $duration $audioMotif->getDuration();
  875.                 } else {
  876.                     $duration $rdv->getDuration();
  877.                 }
  878.                 $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  879.                 /** @var Rdv[] */
  880.                 $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  881.                     ->findAllReviewsCentre($rdvCentre->getId());
  882.                 $rdvItem = [
  883.                     "id" => $rdv->getId(),
  884.                     "motif_id" => $rdv->getIdMotif()->getId(),
  885.                     "duration" => $duration,
  886.                     "color" => $audioMotif->getColor(),
  887.                     "audio_id" => $rdv->getIdAudio()->getId(),
  888.                     "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  889.                     "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  890.                     "client_id" => $rdv->getIdClient()->getId(),
  891.                     "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() . " " $rdv->getIdProche()->getLastname() : $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname(),
  892.                     "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  893.                     "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  894.                     "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  895.                     "testclient" => $rdv->getTestClient() ? [
  896.                         "result" => $rdv->getTestClient()->getResultTonal(),
  897.                         "date" => $rdv->getTestClient()->getDate(),
  898.                         "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  899.                     ] : null,
  900.                     "name" => $rdvCentre->getName(),
  901.                     "phone" => $rdvCentre->getPhone(),
  902.                     "imgUrl" => $rdvCentre->getImgUrl(),
  903.                     "address" => $rdvCentre->getAddress(),
  904.                     "postale" => $rdvCentre->getPostale(),
  905.                     "city" => $rdvCentre->getCity(),
  906.                     "etat_id" => $rdvCentre->getId(),
  907.                     "averageRating" => $publicFunction->calculateRating($centreRdvs),
  908.                     "nbrReview" => count($centreRdvs),
  909.                     "acceptedCurrency" => "CB Chèque",
  910.                     "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  911.                     "note" => $rdv->getNote(),
  912.                     "comment" => $rdv->getComment(),
  913.                     "review" => $rdv->getReview(),
  914.                 ];
  915.                 $rdvResult->add($rdvItem);
  916.             }
  917.         }
  918.         if (count($rdvResult) > 0) {
  919.             return new Response(json_encode(([
  920.                 "rdv" => $rdvResult->toArray(),
  921.                 "status" => 200,
  922.             ])));
  923.         } else {
  924.             return new Response(json_encode(([
  925.                 "message" => "Aucun rendez-vous a venir!",
  926.                 'path' => 'src/Controller/RdvController.php',
  927.                 "status" => 404,
  928.             ])));
  929.         }
  930.     }
  931.     /**
  932.      * @Route("/rdvs/old/client/{id}/centre", name="getOldRdvsByClientIdForCentre", methods={"GET","HEAD"})
  933.      */
  934.     public function getOldRdvsByClientIdForCentre(Request $requestClient $clientPublicFunction $publicFunction)
  935.     {
  936.         if (!$request->query->get('token')) {
  937.             return new Response(json_encode([
  938.                 "message" => "Pas de token n'a été spécifié",
  939.                 "status" => 401,
  940.             ]), 401);
  941.         }
  942.         $entityManager $this->getDoctrine()->getManager();
  943.         /** @var Token */
  944.         $token $this->getDoctrine()
  945.             ->getRepository(Token::class)
  946.             ->findOneBy(['token' => $request->query->get('token')]);
  947.         if (!$token) {
  948.             return new Response(json_encode([
  949.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  950.                 "status" => 404,
  951.             ]), 404);
  952.         }
  953.         $audio $this->getDoctrine()
  954.             ->getRepository(Audio::class)
  955.             ->findOneBy(['id' => $request->query->get('audio')]);
  956.         $audioCentre $this->getDoctrine()
  957.             ->getRepository(AudioCentre::class)
  958.             ->findOneBy(['id_audio' => $audio]);
  959.         // get token age
  960.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  961.         // if the token if older than 7 days
  962.         if ($dateDiff->7) {
  963.             $entityManager->remove($token);
  964.             $entityManager->flush();
  965.             return $this->json([
  966.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  967.                 'path' => 'src/Controller/ClientController.php',
  968.                 "status" => 401,
  969.             ], 401);
  970.         }
  971.         if ($token->getIdClient()) {
  972.             if ($client != $token->getIdClient()) {
  973.                 return new Response(json_encode([
  974.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  975.                     "status" => 404,
  976.                 ]), 404);
  977.             }
  978.         } else if ($token->getIdAudio()) {
  979.             /** @var Token */
  980.             if ($token->getIdAudio() != $audio) {
  981.                 return new Response(json_encode([
  982.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  983.                     "status" => 404,
  984.                 ]), 404);
  985.             }
  986.         } else {
  987.             return new Response(json_encode([
  988.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  989.                 "status" => 404,
  990.             ]), 404);
  991.         }
  992.         if ($request->query->get('audio')) {
  993.             /** @var ActivityRepository */
  994.             $activityRepo $this->getDoctrine();
  995.             if ($request->query->get('limit')) {
  996.                 /** @var Rdv[] */
  997.                 $rdvs $activityRepo
  998.                     ->getRepository(Rdv::class)
  999.                     ->findLastsOldRdvCentresWithLimit($request->query->get('limit'), $client->getId(), $audioCentre->getIdCentre()->getId(), new DateTime());
  1000.                 $rdvResult = new ArrayCollection();
  1001.             } else {
  1002.                 /** @var Rdv[] */
  1003.                 $rdvs $activityRepo
  1004.                     ->getRepository(Rdv::class)
  1005.                     ->findOldRdvsByCentre($client->getId(), $audioCentre->getIdCentre()->getId(), new DateTime());
  1006.                 $rdvResult = new ArrayCollection();
  1007.             }
  1008.             //dd($rdvs);
  1009.             foreach ($rdvs as $rdv) {
  1010.                 // we comment this becoz it was just the validate , we implment other choice select
  1011.                 /* if ($rdv->getIdEtat()->getId() != 5) {
  1012.                     continue;
  1013.                 }*/
  1014.                 /** @var AudioMotif */
  1015.                 $audioMotif $this->getDoctrine()
  1016.                     ->getRepository(AudioMotif::class)
  1017.                     ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  1018.                 if (!$audioMotif) {
  1019.                     continue;
  1020.                 }
  1021.                 $duration '';
  1022.                 if (is_null($rdv->getDuration())) {
  1023.                     $duration $audioMotif->getDuration();
  1024.                 } else {
  1025.                     $duration $rdv->getDuration();
  1026.                 }
  1027.                 $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  1028.                 /** @var Rdv[] */
  1029.                 $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  1030.                     ->findAllReviewsCentre($rdvCentre->getId());
  1031.                 $rdvItem = [
  1032.                     "id" => $rdv->getId(),
  1033.                     "motif_id" => $rdv->getIdMotif()->getId(),
  1034.                     "duration" => $duration,
  1035.                     "color" => $audioMotif->getColor(),
  1036.                     "audio_id" => $rdv->getIdAudio()->getId(),
  1037.                     "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  1038.                     "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  1039.                     "client_id" => $rdv->getIdClient()->getId(),
  1040.                     "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() . " " $rdv->getIdProche()->getLastname() : $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname(),
  1041.                     "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  1042.                     "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  1043.                     "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  1044.                     "testclient" => $rdv->getTestClient() ? [
  1045.                         "result" => $rdv->getTestClient()->getResultTonal(),
  1046.                         "date" => $rdv->getTestClient()->getDate(),
  1047.                         "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  1048.                     ] : null,
  1049.                     "name" => $rdvCentre->getName(),
  1050.                     "phone" => $rdvCentre->getPhone(),
  1051.                     "imgUrl" => $rdvCentre->getImgUrl(),
  1052.                     "address" => $rdvCentre->getAddress(),
  1053.                     "postale" => $rdvCentre->getPostale(),
  1054.                     "city" => $rdvCentre->getCity(),
  1055.                     "etat_id" => $rdvCentre->getId(),
  1056.                     "averageRating" => $publicFunction->calculateRating($centreRdvs),
  1057.                     "nbrReview" => count($centreRdvs),
  1058.                     "acceptedCurrency" => "CB Chèque",
  1059.                     "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  1060.                     "note" => $rdv->getNote(),
  1061.                     "comment" => $rdv->getComment(),
  1062.                     "review" => $rdv->getReview(),
  1063.                     "status" => $rdv->getIdEtat()->getLibelle()
  1064.                 ];
  1065.                 $rdvResult->add($rdvItem);
  1066.             }
  1067.         }
  1068.         if (count($rdvResult) > 0) {
  1069.             return new Response(json_encode(([
  1070.                 "rdv" => $rdvResult->toArray(),
  1071.                 "status" => 200,
  1072.             ])));
  1073.         } else {
  1074.             return new Response(json_encode(([
  1075.                 "message" => "Aucun rendez-vous n'a été trouvé!",
  1076.                 'path' => 'src/Controller/RdvController.php',
  1077.                 "status" => 404,
  1078.             ])));
  1079.         }
  1080.     }
  1081.     private function getOpeningHours($centerId)
  1082.     {
  1083.         $center $this->getDoctrine()->getRepository(Centre::class)->find($centerId);
  1084.         $audioCentre $this->getDoctrine()->getRepository(AudioCentre::class)
  1085.             ->findOneBy(['id_centre' => $center->getId(), 'id_audio' => $center->getIdGerant()->getId()]);
  1086.         $schedule $audioCentre->getHoraire();
  1087.         $availableHours = [];
  1088.         if (isset($schedule['fixed'])) {
  1089.             foreach ($schedule['fixed'] as $day => $hours) {
  1090.                 $dayInFrench strtolower($day);
  1091.                 $slots = [];
  1092.                 foreach ($hours as $period) {
  1093.                     $start strtotime($period['open']);
  1094.                     $end strtotime($period['close']);
  1095.                     while ($start $end) {
  1096.                         $slots[] = date('H:i'$start);
  1097.                         $start strtotime('+30 minutes'$start);
  1098.                     }
  1099.                 }
  1100.                 $availableHours[$dayInFrench] = $slots;
  1101.             }
  1102.         }
  1103.         if (isset($schedule['exceptionalOpened'])) {
  1104.             foreach ($schedule['exceptionalOpened'] as $exception) {
  1105.                 $dayOfWeek strtolower(date('l'strtotime($exception['open'])));
  1106.                 $start strtotime($exception['open']);
  1107.                 $end strtotime($exception['close']);
  1108.                 $exceptionSlots = [];
  1109.                 while ($start $end) {
  1110.                     $exceptionSlots[] = date('H:i'$start);
  1111.                     $start strtotime('+30 minutes'$start);
  1112.                 }
  1113.                 $availableHours[$dayOfWeek] = array_merge(
  1114.                     $availableHours[$dayOfWeek] ?? [],
  1115.                     $exceptionSlots
  1116.                 );
  1117.             }
  1118.         }
  1119.         if (isset($schedule['exceptionalClosed'])) {
  1120.             foreach ($schedule['exceptionalClosed'] as $exception) {
  1121.                 $dayOfWeek strtolower(date('l'strtotime($exception['open'])));
  1122.                 unset($availableHours[$dayOfWeek]);
  1123.             }
  1124.         }
  1125.         return $availableHours;
  1126.     }
  1127.     private function getBookedSlotsForDate($centerId$date)
  1128.     {
  1129.         $bookedSlots $this->getDoctrine()
  1130.             ->getRepository(Rdv::class)
  1131.             ->getBookedSlotsForDate($centerId$date);
  1132.         return $bookedSlots;
  1133.     }
  1134.     private function getAvailableSlotsForDate($openingHours$centerId$date)
  1135.     {
  1136.         $dayOfWeek date('l'strtotime($date));
  1137.         $dayInFrench $this->convertDayToFrench($dayOfWeek);
  1138.         if (!$dayInFrench) {
  1139.             throw new \Exception("Invalid day of the week: $dayOfWeek");
  1140.         }
  1141.         $slots $openingHours[$dayInFrench] ?? [];
  1142.         $bookedSlots $this->getBookedSlotsForDate($centerId$date);
  1143.         $bookedTimes = [];
  1144.         foreach ($bookedSlots as $bookedSlot) {
  1145.             $startTime $bookedSlot['date'];
  1146.             $duration $bookedSlot['duration'];
  1147.             $endTime = (clone $startTime)->modify("+$duration minutes");
  1148.             $bookedTimes[] = ['start' => $startTime'end' => $endTime];
  1149.         }
  1150.         $availableSlots = [];
  1151.         foreach ($slots as $slot) {
  1152.             $slotTime \DateTime::createFromFormat('H:i'$slot);
  1153.             $slotTime->setDate(date('Y'strtotime($date)), date('m'strtotime($date)), date('d'strtotime($date)));
  1154.             if (!$slotTime) {
  1155.                 continue;
  1156.             }
  1157.             $isAvailable true;
  1158.             foreach ($bookedTimes as $bookedTime) {
  1159.                 if ($slotTime >= $bookedTime['start'] && $slotTime $bookedTime['end']) {
  1160.                     $isAvailable false;
  1161.                     break;
  1162.                 }
  1163.             }
  1164.             if ($isAvailable) {
  1165.                 $availableSlots[] = $slot;
  1166.             }
  1167.         }
  1168.         return $availableSlots;
  1169.     }
  1170.     private function convertDayToFrench($englishDay)
  1171.     {
  1172.         $daysMap = [
  1173.             'monday' => 'lundi',
  1174.             'tuesday' => 'mardi',
  1175.             'wednesday' => 'mercredi',
  1176.             'thursday' => 'jeudi',
  1177.             'friday' => 'vendredi',
  1178.             'saturday' => 'samedi',
  1179.             'sunday' => 'dimanche'
  1180.         ];
  1181.         return $daysMap[strtolower($englishDay)] ?? null;
  1182.     }
  1183.     /**
  1184.      * @Route("/audio/{id}/rdvs/", name="getAudioRdvs", methods={"GET","HEAD"})
  1185.      */
  1186.     public function getAudioRdvs(Request $requestAudio $audio)
  1187.     {
  1188.         if (!$request->query->get('token')) {
  1189.             return new Response(json_encode([
  1190.                 "message" => "Pas de token n'a été spécifié",
  1191.                 "status" => 401,
  1192.             ]), 401);
  1193.         }
  1194.         $entityManager $this->getDoctrine()->getManager();
  1195.         /** @var Token */
  1196.         $token $this->getDoctrine()
  1197.             ->getRepository(Token::class)
  1198.             ->findOneBy(['token' => $request->query->get('token')]);
  1199.         if (!$token) {
  1200.             return new Response(json_encode([
  1201.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1202.                 "status" => 404,
  1203.             ]), 404);
  1204.         }
  1205.         // get token age
  1206.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1207.         // if the token if older than 7 days
  1208.         if ($dateDiff->7) {
  1209.             $entityManager->remove($token);
  1210.             $entityManager->flush();
  1211.             return $this->json([
  1212.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1213.                 'path' => 'src/Controller/ClientController.php',
  1214.                 "status" => 401,
  1215.             ], 401);
  1216.         }
  1217.         if ($audio != $token->getIdAudio()) {
  1218.             return new Response(json_encode([
  1219.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  1220.                 "status" => 404,
  1221.             ]), 404);
  1222.         }
  1223.         $centre = (int)$request->query->get('centre');
  1224.         if (($request->query->get('debut')) && ($request->query->get('fin'))) {
  1225.             $rdvs $this->getDoctrine()
  1226.                 ->getRepository(Rdv::class)
  1227.                 ->findBetweenDate(
  1228.                     $audio->getId(),
  1229.                     new DateTime($request->query->get('debut')),
  1230.                     new DateTime($request->query->get('fin')),
  1231.                     $centre // Le centre est maintenant un entier
  1232.                 );
  1233.         } else {
  1234.             $rdvs $this->getDoctrine()
  1235.                 ->getRepository(Rdv::class)
  1236.                 ->findBy(['id_audio' => $audio->getId()]);
  1237.         }
  1238.         $rdvResult = new ArrayCollection();
  1239.         $centerId $request->query->get('centre');
  1240.         // $openingHours = $this->getOpeningHours($centerId); 
  1241.         $centerId $request->query->get('centre');
  1242.         $dateCache = new \DateTime();
  1243.         $openingHours $this->cache->get('centre_' $centerId '_horaires_' $dateCache->format('Y-m-d'), function (ItemInterface $item) use ($centerId$dateCache) {
  1244.             $item->expiresAfter(7200);
  1245.             return $this->getOpeningHours($centerId);
  1246.         });
  1247.         //dd($openingHours);
  1248.         foreach ($rdvs as $rdv) {
  1249.             if ($rdv->getIdEtat()->getId() != null) {
  1250.                 if ($rdv->getIsAbsence() != 1) {
  1251.                     /** @var AudioMotif */
  1252.                     $audioMotif $this->getDoctrine()
  1253.                         ->getRepository(AudioMotif::class)
  1254.                         ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $audio->getId()]);
  1255.                     if (!isset($audioMotif)) {
  1256.                         continue;
  1257.                     }
  1258.                     $motif $this->getDoctrine()
  1259.                         ->getRepository(Motif::class)
  1260.                         ->findOneBy(['id' => $rdv->getIdMotif()->getId()]);
  1261.                     $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  1262.                     if ($rdv->getIdClientTemp()) {
  1263.                         $confiance "";
  1264.                     } else {
  1265.                         $confiance $client->getIdPersonneConfiance() ? $client->getIdPersonneConfiance()->getId() : null;
  1266.                     }
  1267.                 }
  1268.                 $duration '';
  1269.                 if (is_null($rdv->getDuration())) {
  1270.                     $duration $audioMotif->getDuration();
  1271.                 } else {
  1272.                     $duration $rdv->getDuration();
  1273.                 }
  1274.                 $dateFin = new DateTime($rdv->getDate()->format('Y-m-d\TH:i:s'));
  1275.                 $dateFin $dateFin->add(new DateInterval("PT" $duration "M"));
  1276.                 if ($rdv->getIdClientTemp()) {
  1277.                     $findNextRdv $this->getDoctrine()
  1278.                         ->getRepository(Rdv::class)
  1279.                         ->findBy([
  1280.                             "id_client_temp" => $rdv->getIdClientTemp(),
  1281.                             "id_motif" => ['106''107''108''109']
  1282.                         ]);
  1283.                 } else {
  1284.                     $findNextRdv $this->getDoctrine()
  1285.                         ->getRepository(Rdv::class)
  1286.                         ->findBy([
  1287.                             "id_client_temp" => $rdv->getIdClient(),
  1288.                             "id_motif" => ['106''107''108''109']
  1289.                         ]);
  1290.                 }
  1291.                 $finalRdv null;
  1292.                 /*if ($rdv->getRdvParent()) {
  1293.     $finalRdv = $this->getDoctrine()
  1294.         ->getRepository(Rdv::class)
  1295.         ->find($rdv->getRdvParent());
  1296. }*/
  1297.                 //if($client->getClientDevices())
  1298.                 //{
  1299.                 //if ($client->getClientDevices()->first()) {
  1300.                 /*$nextRdv = $this->getDoctrine()
  1301.                  ->getRepository(Rdv::class)
  1302.                  ->find($finalRdv->getClientDevice()->getRdv()->getId());*/
  1303.                 //  }
  1304.                 //}
  1305.                 if ($rdv->getIsAbsence() != 1) {
  1306.                     if ($rdv->getIdClientTemp()) {
  1307.                         $nextRdvs $this->getDoctrine()
  1308.                             ->getRepository(Rdv::class)
  1309.                             ->findBy([
  1310.                                 "id_client_temp" => $client,
  1311.                                 "id_motif" => ['106''107''108''109']
  1312.                             ]);
  1313.                     } else {
  1314.                         $nextRdvs $this->getDoctrine()
  1315.                             ->getRepository(Rdv::class)
  1316.                             ->findBy([
  1317.                                 "id_client" => $client,
  1318.                                 "id_motif" => ['106''107''108''109']
  1319.                             ]);
  1320.                     }
  1321.                     if ($client->getClientDevices()) {
  1322.                         if ($client->getClientDevices()->first()) {
  1323.                             if (empty($nextRdvs)) {
  1324.                                 $isNextRdv false;
  1325.                                 $initialRdvDate $rdv->getDate();
  1326.                                 $availableSlots = [
  1327.                                     'Suivie de l’essai' => $this->findFirstAvailableSlot($centerId$initialRdvDate7),
  1328.                                     'Confirmation de l’essai' => $this->findFirstAvailableSlot($centerId$initialRdvDate14),
  1329.                                     'Validation de l’appareillage' => $this->findFirstAvailableSlot($centerId$initialRdvDate21),
  1330.                                     'Facturation de l’appareillage' => $this->findFirstAvailableSlot($centerId$initialRdvDate30),
  1331.                                     'duration' => "30"
  1332.                                 ];
  1333.                                 $mappedNextRdvs = [
  1334.                                     'Suivie de l’essai' => $this->findAvailableDay($centerId$initialRdvDate7),
  1335.                                     'Confirmation de l’essai' => $this->findAvailableDay($centerId$initialRdvDate14),
  1336.                                     'Validation de l’appareillage' => $this->findAvailableDay($centerId$initialRdvDate21),
  1337.                                     'Facturation de l’appareillage' => $this->findAvailableDay($centerId$initialRdvDate30),
  1338.                                     'duration' => "30"
  1339.                                 ];
  1340.                             } else {
  1341.                                 $isNextRdv true;
  1342.                                 $initialRdvDate $rdv->getDate();
  1343.                                 // Available slots for each follow-up date
  1344.                                 $availableSlots = [];
  1345.                                 if (isset($nextRdvs[0])) {
  1346.                                     $availableSlots['Suivie de l’essai'] = $this->getAvailableSlotsForDate(
  1347.                                         $openingHours,
  1348.                                         $centerId,
  1349.                                         $nextRdvs[0]->getDate()->format('Y-m-d')
  1350.                                     );
  1351.                                 }
  1352.                                 if (isset($nextRdvs[1])) {
  1353.                                     $availableSlots['Confirmation de l’essai'] = $this->getAvailableSlotsForDate(
  1354.                                         $openingHours,
  1355.                                         $centerId,
  1356.                                         $nextRdvs[1]->getDate()->format('Y-m-d')
  1357.                                     );
  1358.                                 }
  1359.                                 if (isset($nextRdvs[2])) {
  1360.                                     $availableSlots['Validation de l’appareillage'] = $this->getAvailableSlotsForDate(
  1361.                                         $openingHours,
  1362.                                         $centerId,
  1363.                                         $nextRdvs[2]->getDate()->format('Y-m-d')
  1364.                                     );
  1365.                                 }
  1366.                                 if (isset($nextRdvs[3])) {
  1367.                                     $availableSlots['Facturation de l’appareillage'] = $this->getAvailableSlotsForDate(
  1368.                                         $openingHours,
  1369.                                         $centerId,
  1370.                                         $nextRdvs[3]->getDate()->format('Y-m-d')
  1371.                                     );
  1372.                                 }
  1373.                                 $mappedNextRdvs array_map(function ($rdv) {
  1374.                                     return [
  1375.                                         'id' => $rdv->getId(),
  1376.                                         'date' => $rdv->getDate()->format('d-m-Y'),
  1377.                                         'hours' => $rdv->getDate()->format('H:i'),
  1378.                                         'duration' => $rdv->getDuration(),
  1379.                                         "motif_id" => $rdv->getIdMotif()->getId(),
  1380.                                         "motif_titre" => $rdv->getIdMotif()->getTitre(),
  1381.                                     ];
  1382.                                 }, $nextRdvs);
  1383.                             }
  1384.                         }
  1385.                     }
  1386.                     $rdvItem = [
  1387.                         "id" => $rdv->getId(),
  1388.                         "motif_id" => $rdv->getIdMotif()->getId(),
  1389.                         "motif_titre" => $motif->getTitre(),
  1390.                         "duration" => $duration,
  1391.                         "color" => $audioMotif->getColor(),
  1392.                         "audio_id" => $rdv->getIdAudio()->getId(),
  1393.                         "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  1394.                         "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  1395.                         "client_id" => $client->getId(),
  1396.                         "isClient" => ($client instanceof Client) ? 0,
  1397.                         "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() : $client->getName(),
  1398.                         "client_lastname" => $rdv->getIdProche() ? $rdv->getIdProche()->getLastname() : $client->getLastname(),
  1399.                         "client_mail" => $client->getMail(),
  1400.                         "client_tel" => $client->getPhone(),
  1401.                         "client_fixe" => $client->getPhoneFixe(),
  1402.                         "confiance" =>  $confiance,
  1403.                         "client_birthday" => $client->getBirthdate() ? $client->getBirthdate()->format("Y-m-d") : null,
  1404.                         "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  1405.                         "centre_id" => $rdv->getIdCentre()->getId(),
  1406.                         "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  1407.                         "testclient" => $rdv->getTestClient() ? [
  1408.                             "result" => $rdv->getTestClient()->getResultTonal(),
  1409.                             "date" => $rdv->getTestClient()->getDate(),
  1410.                             "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  1411.                         ] : null,
  1412.                         "name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : $rdv->getIdLieu()->getName(),
  1413.                         "centerName" => $rdv->getIdCentre()->getName(),
  1414.                         "phone" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getPhone() : $rdv->getIdLieu()->getPhone(),
  1415.                         "etat_id" => $rdv->getIdEtat()->getId(),
  1416.                         "clientEtatId" => $client->getClientStatus() ? $client->getClientStatus()->getId() : 0,
  1417.                         "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  1418.                         "dateFin" => $dateFin->format('Y-m-d\TH:i:s'),
  1419.                         "comment" => $rdv->getComment(),
  1420.                         "note" => $rdv->getNote(),
  1421.                         "isTemp" => $rdv->getIdClientTemp() ? 0,
  1422.                         "isAbsence" => $rdv->getIsAbsence(),
  1423.                         "device" => $client->getClientDevices()->first() ? [
  1424.                             "isDevice" => true,
  1425.                             "isNextRdv" => $isNextRdv,
  1426.                             "deviceID" => $client->getClientDevices()->first()->getDevice()->getId(),
  1427.                             "clientDeviceID" => $client->getClientDevices()->first()->getId(),
  1428.                             "deviceModel" => $client->getClientDevices()->first()->getDevice()->getModel(),
  1429.                             "settingDeviceId" => $client->getClientDevices()->first()->getSettingDevice()->getSlug(),
  1430.                             "settingName" => $client->getClientDevices()->first()->getSettingDevice()->getName(),
  1431.                             "settingSlug" => $client->getClientDevices()->first()->getSettingDevice()->getSlug(),
  1432.                             "nextRdvs" => $mappedNextRdvs,
  1433.                             "available_slots" => $availableSlots
  1434.                         ] : [
  1435.                             "isDevice" => false
  1436.                         ]
  1437.                     ];
  1438.                 } else {
  1439.                     // $clientDevice = $client->getClientDevices()->first();
  1440.                     $rdvItem = [
  1441.                         "id" => $rdv->getId(),
  1442.                         "duration" => $duration,
  1443.                         "color" => $rdv->getColor() ? $rdv->getColor() . '66' '#ffb2b266',
  1444.                         "audio_id" => $rdv->getIdAudio()->getId(),
  1445.                         "client_id" =>  "",
  1446.                         "isClient" => false,
  1447.                         "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  1448.                         "centre_id" => $rdv->getIdCentre()->getId(),
  1449.                         "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  1450.                         "name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : $rdv->getIdLieu()->getName(),
  1451.                         "phone" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getPhone() : $rdv->getIdLieu()->getPhone(),
  1452.                         "etat_id" => $rdv->getIdEtat()->getId(),
  1453.                         "clientEtatId" => "",
  1454.                         "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  1455.                         "dateFin" => $dateFin->format('Y-m-d\TH:i:s'),
  1456.                         "note" => $rdv->getNote(),
  1457.                         "device" => "",
  1458.                         "centerName" => $rdv->getIdCentre()->getName(),
  1459.                         "isTemp" => $rdv->getIdClientTemp() ? 0,
  1460.                         "isAbsence" => $rdv->getIsAbsence(),
  1461.                         "motif_titre" => $rdv->getMotifAbsence() ? $rdv->getMotifAbsence() : "Absence",
  1462.                     ];
  1463.                 }
  1464.                 //  if ($rdv->getDate() >= new DateTime())
  1465.                 $rdvResult->add($rdvItem);
  1466.             }
  1467.         }
  1468.         if (count($rdvResult) > 0) {
  1469.             return new Response(json_encode(([
  1470.                 "content" => $rdvResult->toArray(),
  1471.                 "status" => 200,
  1472.                 "datefin" => $dateFin
  1473.             ])));
  1474.         } else {
  1475.             $rdvItem = [];
  1476.             //$rdvResult->add($rdvItem);
  1477.             return new Response(json_encode(([
  1478.                 "content" => $rdvResult->toArray(),
  1479.                 "message" => "Aucun rendez-vous n'a été trouvé!",
  1480.                 'path' => 'src/Controller/RdvController.php',
  1481.                 "status" => 404,
  1482.             ])));
  1483.         }
  1484.     }
  1485.     private function findAvailableDay(int $centerId\DateTime $initialRdvDateint $offset): string
  1486.     {
  1487.         $currentDate = (clone $initialRdvDate)->modify("+{$offset} days");
  1488.         while (true) {
  1489.             $formattedDate $currentDate->format('Y-m-d');
  1490.             $slots $this->getAvailableSlotsForDate(
  1491.                 $this->getOpeningHoursList($centerId$formattedDate),
  1492.                 $centerId,
  1493.                 $formattedDate
  1494.             );
  1495.             if (!empty($slots)) {
  1496.                 return $formattedDate;
  1497.             }
  1498.             $currentDate->modify('+1 day');
  1499.         }
  1500.     }
  1501.     private function findFirstAvailableSlot(int $centerId\DateTime $initialRdvDateint $offset): array
  1502.     {
  1503.         $currentDate = (clone $initialRdvDate)->modify("+{$offset} days");
  1504.         while (true) {
  1505.             $formattedDate $currentDate->format('Y-m-d');
  1506.             $slots $this->getAvailableSlotsForDate(
  1507.                 $this->getOpeningHoursList($centerId$formattedDate),
  1508.                 $centerId,
  1509.                 $formattedDate
  1510.             );
  1511.             if (!empty($slots)) {
  1512.                 return $slots;
  1513.             }
  1514.             $currentDate->modify('+1 day');
  1515.         }
  1516.     }
  1517.     private function getOpeningHoursList($centerId$date)
  1518.     {
  1519.         $center $this->getDoctrine()->getRepository(Centre::class)->find($centerId);
  1520.         $audioCentre $this->getDoctrine()->getRepository(AudioCentre::class)
  1521.             ->findOneBy(['id_centre' => $center->getId(), 'id_audio' => $center->getIdGerant()->getId()]);
  1522.         $schedule $audioCentre->getHoraire();
  1523.         $availableHours = [];
  1524.         $holidayDates = [
  1525.             'JourdelAn' => '01-01',
  1526.             'LundidePâques' => '21-04',
  1527.             'FêteduTravail' => '01-05',
  1528.             'Victoire1945' => '08-05',
  1529.             'Ascension' => '29-05',
  1530.             'LundidePentecôte' => '09-06',
  1531.             'FêteNationale' => '14-07',
  1532.             'Assomption' => '15-08',
  1533.             'Toussaint' => '01-11',
  1534.             'Armistice1918' => '11-11',
  1535.             'Noël' => '25-12',
  1536.         ];
  1537.         $holidays $center->getHorairesHoliday();
  1538.         $requestDate date('d-m'strtotime($date));
  1539.         $englishToFrenchDays = [
  1540.             'monday' => 'lundi',
  1541.             'tuesday' => 'mardi',
  1542.             'wednesday' => 'mercredi',
  1543.             'thursday' => 'jeudi',
  1544.             'friday' => 'vendredi',
  1545.             'saturday' => 'samedi',
  1546.             'sunday' => 'dimanche',
  1547.         ];
  1548.         $dayOfWeek strtolower(date('l'strtotime($date)));
  1549.         $dayInFrench $englishToFrenchDays[$dayOfWeek];
  1550.         if (isset($schedule['fixed'])) {
  1551.             foreach ($schedule['fixed'] as $day => $hours) {
  1552.                 $dayKey strtolower($day);
  1553.                 $slots = [];
  1554.                 foreach ($hours as $period) {
  1555.                     $start strtotime($period['open']);
  1556.                     $end strtotime($period['close']);
  1557.                     while ($start $end) {
  1558.                         $slots[] = date('H:i'$start);
  1559.                         $start strtotime('+30 minutes'$start);
  1560.                     }
  1561.                 }
  1562.                 $availableHours[$dayKey] = $slots;
  1563.             }
  1564.         }
  1565.         foreach ($holidays['fixed'] as $holiday => $hours) {
  1566.             if (isset($holidayDates[$holiday]) && $holidayDates[$holiday] === $requestDate) {
  1567.                 $holidaySlots = [];
  1568.                 if (!empty($hours)) {
  1569.                     foreach ($hours as $period) {
  1570.                         $start strtotime($period['open']);
  1571.                         $end strtotime($period['close']);
  1572.                         while ($start $end) {
  1573.                             $holidaySlots[] = date('H:i'$start);
  1574.                             $start strtotime('+30 minutes'$start);
  1575.                         }
  1576.                     }
  1577.                     $availableHours[$dayInFrench] = $holidaySlots;
  1578.                 } else {
  1579.                     $availableHours[$dayInFrench] = [];
  1580.                 }
  1581.                 break;
  1582.             }
  1583.         }
  1584.         return $availableHours;
  1585.     }
  1586.     /**
  1587.      * @Route("/audio/{id}/rdvsTest/", name="getAudioRdvsTest", methods={"GET","HEAD"})
  1588.      */
  1589.     public function getAudioRdvsTest(Request $requestAudio $audio)
  1590.     {
  1591.         if (!$request->query->get('token')) {
  1592.             return new Response(json_encode([
  1593.                 "message" => "Pas de token n'a été spécifié",
  1594.                 "status" => 401,
  1595.             ]), 401);
  1596.         }
  1597.         $entityManager $this->getDoctrine()->getManager();
  1598.         /** @var Token */
  1599.         $token $this->getDoctrine()
  1600.             ->getRepository(Token::class)
  1601.             ->findOneBy(['token' => $request->query->get('token')]);
  1602.         if (!$token) {
  1603.             return new Response(json_encode([
  1604.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1605.                 "status" => 404,
  1606.             ]), 404);
  1607.         }
  1608.         // get token age
  1609.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1610.         // if the token if older than 7 days
  1611.         if ($dateDiff->7) {
  1612.             $entityManager->remove($token);
  1613.             $entityManager->flush();
  1614.             return $this->json([
  1615.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1616.                 'path' => 'src/Controller/ClientController.php',
  1617.                 "status" => 401,
  1618.             ], 401);
  1619.         }
  1620.         if ($audio != $token->getIdAudio()) {
  1621.             return new Response(json_encode([
  1622.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  1623.                 "status" => 404,
  1624.             ]), 404);
  1625.         }
  1626.         /** @var Rdv[] */
  1627.         if (($request->query->get('debut')) && ($request->query->get('fin'))) {
  1628.             $rdvs $this->getDoctrine()
  1629.                 ->getRepository(Rdv::class)
  1630.                 ->findBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1631.         } else {
  1632.             $rdvs $this->getDoctrine()
  1633.                 ->getRepository(Rdv::class)
  1634.                 ->findBy(['id_audio' => $audio->getId()]);
  1635.         }
  1636.         $rdvResult = new ArrayCollection();
  1637.         foreach ($rdvs as $rdv) {
  1638.             if ($rdv->getIdEtat()->getId() != null) {
  1639.                 /** @var AudioMotif */
  1640.                 $audioMotif $this->getDoctrine()
  1641.                     ->getRepository(AudioMotif::class)
  1642.                     ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $audio->getId()]);
  1643.                 if (!isset($audioMotif)) {
  1644.                     continue;
  1645.                 }
  1646.                 $motif $this->getDoctrine()
  1647.                     ->getRepository(Motif::class)
  1648.                     ->findOneBy(['id' => $rdv->getIdMotif()->getId()]);
  1649.                 $dateFin = new DateTime($rdv->getDate()->format('Y-m-d H:i:s'));
  1650.                 $dateFin $dateFin->add(new DateInterval("PT" $audioMotif->getDuration() . "M"));
  1651.                 $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  1652.                 $name $rdv->getIdProche() ? $rdv->getIdProche()->getName() : $client->getName();
  1653.                 $lastName $rdv->getIdProche() ? $rdv->getIdProche()->getLastname() : $client->getLastname();
  1654.                 $rdvItem = [
  1655.                     "id" => $rdv->getId(),
  1656.                     "title" => $lastName ' ' $name,
  1657.                     "start" => $rdv->getDate()->format('Y-m-d H:i:s'),
  1658.                     "end"   => $dateFin->format('Y-m-d H:i:s'),
  1659.                     "backgroundColor" => $audioMotif->getColor(),
  1660.                     "editable" => true,
  1661.                     "durationEditable" => false,
  1662.                     "resourceEditable" => true,
  1663.                     "cache" => false,
  1664.                     "motif_id" => $rdv->getIdMotif()->getId(),
  1665.                     "motif" => $motif->getTitre(),
  1666.                     "duree" => $audioMotif->getDuration(),
  1667.                     "color" => $audioMotif->getColor(),
  1668.                     "color_motif" => $audioMotif->getColor(),
  1669.                     "client_id" => $client->getId(),
  1670.                     "clientName" => $name,
  1671.                     "clientLastName" => $lastName,
  1672.                     "mail" => $client->getMail(),
  1673.                     "telephone" => $client->getPhone(),
  1674.                     "birthday" => $client->getBirthdate(),
  1675.                     "etat_id" => $rdv->getIdEtat()->getId(),
  1676.                     "dateDeb" => $rdv->getDate()->format('Y-m-d H:i:s'),
  1677.                     "dateFin" => $dateFin->format('Y-m-d H:i:s'),
  1678.                     "commentaire" => $rdv->getNote(),
  1679.                     "event_title" => "<b>" $lastName "</b> " $name,
  1680.                 ];
  1681.                 //  if ($rdv->getDate() >= new DateTime())
  1682.                 $rdvResult->add($rdvItem);
  1683.             }
  1684.         }
  1685.         if (count($rdvResult) > 0) {
  1686.             return new Response(json_encode(
  1687.                 $rdvResult->toArray(),
  1688.             ));
  1689.         } else {
  1690.             $rdvItem = [];
  1691.             //$rdvResult->add($rdvItem);
  1692.             return new Response(json_encode(
  1693.                 $rdvResult->toArray(),
  1694.             ));
  1695.         }
  1696.     }
  1697.     /**
  1698.      * @Route("/audio/{id}/rdvs/count", name="getCountAudioRdvs", methods={"GET","HEAD"})
  1699.      */
  1700.     public function getCountAudioRdvs(Request $requestAudio $audio)
  1701.     {
  1702.         if (!$request->query->get('token')) {
  1703.             return new Response(json_encode([
  1704.                 "message" => "Pas de token n'a été spécifié",
  1705.                 "status" => 401,
  1706.             ]), 401);
  1707.         }
  1708.         $entityManager $this->getDoctrine()->getManager();
  1709.         /** @var Token */
  1710.         $token $this->getDoctrine()
  1711.             ->getRepository(Token::class)
  1712.             ->findOneBy(['token' => $request->query->get('token')]);
  1713.         if (!$token) {
  1714.             return new Response(json_encode([
  1715.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1716.                 "status" => 404,
  1717.             ]), 404);
  1718.         }
  1719.         // get token age
  1720.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1721.         // if the token if older than 7 days
  1722.         if ($dateDiff->7) {
  1723.             $entityManager->remove($token);
  1724.             $entityManager->flush();
  1725.             return $this->json([
  1726.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1727.                 'path' => 'src/Controller/ClientController.php',
  1728.                 "status" => 401,
  1729.             ], 401);
  1730.         }
  1731.         if ($audio != $token->getIdAudio()) {
  1732.             return new Response(json_encode([
  1733.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  1734.                 "status" => 404,
  1735.             ]), 404);
  1736.         }
  1737.         /** @var Rdv[] */
  1738.         $rdvs $this->getDoctrine()
  1739.             ->getRepository(Rdv::class)
  1740.             ->findBy(['id_audio' => $audio->getId()]);
  1741.         return new Response(json_encode(([
  1742.             "content" => count($rdvs),
  1743.             "status" => 200,
  1744.         ])));
  1745.     }
  1746.     /**
  1747.      * @Route("/audio/{id}/rdvsDate/count", name="getCountAudioRdvsBetweenDate", methods={"GET","HEAD"})
  1748.      */
  1749.     public function getCountAudioRdvsBetweenDate(Request $requestAudio $audio)
  1750.     {
  1751.         if (!$request->query->get('token')) {
  1752.             return new Response(json_encode([
  1753.                 "message" => "Pas de token n'a été spécifié",
  1754.                 "status" => 401,
  1755.             ]), 401);
  1756.         }
  1757.         $entityManager $this->getDoctrine()->getManager();
  1758.         /** @var Token */
  1759.         $token $this->getDoctrine()
  1760.             ->getRepository(Token::class)
  1761.             ->findOneBy(['token' => $request->query->get('token')]);
  1762.         if (!$token) {
  1763.             return new Response(json_encode([
  1764.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1765.                 "status" => 404,
  1766.             ]), 404);
  1767.         }
  1768.         // get token age
  1769.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1770.         // if the token if older than 7 days
  1771.         if ($dateDiff->7) {
  1772.             $entityManager->remove($token);
  1773.             $entityManager->flush();
  1774.             return $this->json([
  1775.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1776.                 'path' => 'src/Controller/ClientController.php',
  1777.                 "status" => 401,
  1778.             ], 401);
  1779.         }
  1780.         if ($audio != $token->getIdAudio()) {
  1781.             return new Response(json_encode([
  1782.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  1783.                 "status" => 404,
  1784.             ]), 404);
  1785.         }
  1786.         /** @var Rdv[] */
  1787.         $allRdvs $this->getDoctrine()
  1788.             ->getRepository(Rdv::class)
  1789.             ->findOnlyRdvAudioBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1790.         /** @var Rdv[] */
  1791.         $rdvs $this->getDoctrine()
  1792.             ->getRepository(Rdv::class)
  1793.             ->findOnlyRdvAudioWithoutTestBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1794.         /** @var Rdv[] */
  1795.         $rdvsWithTest $this->getDoctrine()
  1796.             ->getRepository(Rdv::class)
  1797.             ->findOnlyRdvAudioWithTestBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1798.         /** @var Rdv[] */
  1799.         $allRdvsCanceled $this->getDoctrine()
  1800.             ->getRepository(Rdv::class)
  1801.             ->findCanceledRdvAudioBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1802.         /** @var Rdv[] */
  1803.         $allRdvsCanceledCentre $this->getDoctrine()
  1804.             ->getRepository(Rdv::class)
  1805.             ->findCanceledRdvCentreBetweenDate(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1806.         /** @var Rdv[] */
  1807.         $rdvsClosed $this->getDoctrine()
  1808.             ->getRepository(Rdv::class)
  1809.             ->findClosedRdvBetweenDate(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1810.         $myLead 0;
  1811.         $rdvsCanceled $this->getDoctrine()
  1812.             ->getRepository(Rdv::class)
  1813.             ->findCanceledRdvAudioBetweenDateWithoutTest($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1814.         foreach ($rdvsCanceled as $rdvc) {
  1815.             if (!is_null($rdvc->getIdClient())) {
  1816.                 $rdvClient $this->getDoctrine()
  1817.                     ->getRepository(Rdv::class)
  1818.                     ->findRDVLeadByClient(new DateTime($request->query->get('debut')), $request->query->get('centre'), $rdvc->getIdClient()->getID());
  1819.                 if (count($rdvClient) == 0) {
  1820.                     $myLead $myLead 1;
  1821.                 }
  1822.             }
  1823.         }
  1824.         $myLeadAdvanced 0;
  1825.         $rdvsCanceledA $this->getDoctrine()
  1826.             ->getRepository(Rdv::class)
  1827.             ->findCanceledRdvAudioBetweenDateWithTest($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1828.         foreach ($rdvsCanceledA as $rdvc) {
  1829.             if (!is_null($rdvc->getIdClient())) {
  1830.                 $rdvClient $this->getDoctrine()
  1831.                     ->getRepository(Rdv::class)
  1832.                     ->findRDVLeadByClient(new DateTime($request->query->get('debut')), $request->query->get('centre'), $rdvc->getIdClient()->getID());
  1833.                 if (count($rdvClient) == 0) {
  1834.                     $myLeadAdvanced $myLeadAdvanced 1;
  1835.                 }
  1836.             }
  1837.         }
  1838.         /**** MY RDV Centre****/
  1839.         $myrdvCentre 0;
  1840.         $rdvs $this->getDoctrine()
  1841.             ->getRepository(Rdv::class)
  1842.             ->findRDVCentreBetweenDateWithoutTest(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1843.         $myrdvCentre count($rdvs);
  1844.         /**** MY RDV ADVANCED ****/
  1845.         $myRdvAdvancedCentre 0;
  1846.         $rdvsA $this->getDoctrine()
  1847.             ->getRepository(Rdv::class)
  1848.             ->findRDVCentreBetweenDateWithTestId(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1849.         $myRdvAdvancedCentre count($rdvsA);
  1850.         /**** FIRST RDV BY MOTIF PREMIER RDV ****/
  1851.         $myFirstRdv 0;
  1852.         $rdvsFirst $this->getDoctrine()
  1853.             ->getRepository(Rdv::class)
  1854.             ->findFirstRdv(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1855.         $myFirstRdv count($rdvsFirst);
  1856.         /****  RDV BY RECHERCHE RESULT VIA MYAUDIO ****/
  1857.         $myAudioRdv 0;
  1858.         $audioRdv $this->getDoctrine()
  1859.             ->getRepository(Rdv::class)
  1860.             ->findRdvMyAudio(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1861.         $myAudioRdv count($audioRdv);
  1862.         /****  RDV BY GENDER ****/
  1863.         $myRdvByGender 0;
  1864.         $audioRdvGender $this->getDoctrine()
  1865.             ->getRepository(Rdv::class)
  1866.             ->countMaleAndFemalePatient(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1867.         $myRdvByGender $audioRdvGender;
  1868.         /****  RDV BY AGE ****/
  1869.         $myRdvByAge 0;
  1870.         $audioRdvAge $this->getDoctrine()
  1871.             ->getRepository(Rdv::class)
  1872.             ->countClientsByAgeGroupsPatient(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1873.         $myRdvByAge $audioRdvAge;
  1874.         //  dd($myRdvByAge);
  1875.         /**** MY LEAD ****/
  1876.         $myLeadCentre 0;
  1877.         $rdvsCanceled $this->getDoctrine()
  1878.             ->getRepository(Rdv::class)
  1879.             ->findCanceledRdvCentreBetweenDateWithoutTest(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1880.         foreach ($rdvsCanceled as $rdvc) {
  1881.             if (!is_null($rdvc->getIdClient())) {
  1882.                 $rdvClient $this->getDoctrine()
  1883.                     ->getRepository(Rdv::class)
  1884.                     ->findRDVLeadByClient(new DateTime($request->query->get('debut')), $request->query->get('centre'), $rdvc->getIdClient()->getID());
  1885.                 if (count($rdvClient) == 0) {
  1886.                     $myLeadCentre $myLeadCentre 1;
  1887.                 }
  1888.             }
  1889.         }
  1890.         /**** MY LEAD ADVANCED****/
  1891.         $myLeadAdvancedCentre 0;
  1892.         $rdvsCanceledA $this->getDoctrine()
  1893.             ->getRepository(Rdv::class)
  1894.             ->findCanceledRdvCentreBetweenDateWithTest(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1895.         foreach ($rdvsCanceledA as $rdvc) {
  1896.             if (!is_null($rdvc->getIdClient())) {
  1897.                 $rdvClient $this->getDoctrine()
  1898.                     ->getRepository(Rdv::class)
  1899.                     ->findRDVLeadByClient(new DateTime($request->query->get('debut')), $request->query->get('centre'), $rdvc->getIdClient()->getID());
  1900.                 if (count($rdvClient) == 0) {
  1901.                     $myLeadAdvancedCentre $myLeadAdvancedCentre 1;
  1902.                 }
  1903.             }
  1904.         }
  1905.         return $this->json([
  1906.             "rdvs" => count($rdvs),
  1907.             "rdvsFromTest" => count($rdvsWithTest),
  1908.             "allRdvs" => count($allRdvs),
  1909.             "rdvsCanceled" => count($allRdvsCanceled),
  1910.             "rdvsClosed" => $rdvsClosed,
  1911.             "myRdvByGender" => $myRdvByGender,
  1912.             "myLead" => $myLead,
  1913.             "myRdvByAge" => $myRdvByAge,
  1914.             "myAudioRdv" => $myAudioRdv,
  1915.             "myLeadAdvanced" => $myLeadAdvanced,
  1916.             "myRDVCentre" => $myrdvCentre,
  1917.             "myRDVAdancedCentre" => $myRdvAdvancedCentre,
  1918.             "myLeadCentre" => $myLeadCentre,
  1919.             "myLeadAdvancedCentre" => $myLeadAdvancedCentre,
  1920.             "rdvsCanceledCentre" => count($allRdvsCanceledCentre),
  1921.             "myFirstRdv" => $myFirstRdv,
  1922.             "status" => 200,
  1923.         ]);
  1924.     }
  1925.     /**
  1926.      * @Route("/rdvs/old/clientTemp/{id}", name="getOldRdvsByClientTempId", methods={"GET","HEAD"})
  1927.      */
  1928.     public function getOldRdvsByClientTempId(Request $requestClientTemp $clientTempPublicFunction $publicFunction)
  1929.     {
  1930.         if (!$request->query->get('token')) {
  1931.             return new Response(json_encode([
  1932.                 "message" => "Pas de token n'a été spécifié",
  1933.                 "status" => 401,
  1934.             ]), 401);
  1935.         }
  1936.         $entityManager $this->getDoctrine()->getManager();
  1937.         /** @var Token */
  1938.         $token $this->getDoctrine()
  1939.             ->getRepository(Token::class)
  1940.             ->findOneBy(['token' => $request->query->get('token')]);
  1941.         if (!$token) {
  1942.             return new Response(json_encode([
  1943.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1944.                 "status" => 404,
  1945.             ]), 404);
  1946.         }
  1947.         // get token age
  1948.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1949.         // if the token if older than 7 days
  1950.         if ($dateDiff->7) {
  1951.             $entityManager->remove($token);
  1952.             $entityManager->flush();
  1953.             return $this->json([
  1954.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1955.                 'path' => 'src/Controller/ClientController.php',
  1956.                 "status" => 401,
  1957.             ], 401);
  1958.         }
  1959.         if ($clientTemp->getIdAudio() != $token->getIdAudio()) {
  1960.             return new Response(json_encode([
  1961.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  1962.                 "status" => 404,
  1963.             ]), 404);
  1964.         }
  1965.         if ($request->query->get('audio')) {
  1966.             /** @var ActivityRepository */
  1967.             $activityRepo $this->getDoctrine()->getRepository(Rdv::class);
  1968.             if ($request->query->get('limit')) {
  1969.                 /** @var Rdv[] */
  1970.                 $rdvs $activityRepo
  1971.                     ->findLastsOldRdvsWithLimitTemp($request->query->get('limit'), $clientTemp->getId(), $request->query->get('audio'), new DateTime());
  1972.                 $rdvResult = new ArrayCollection();
  1973.             } else {
  1974.                 /** @var Rdv[] */
  1975.                 $rdvs $activityRepo
  1976.                     ->findOldRdvsTemp($clientTemp->getId(), $request->query->get('audio'), new DateTime());
  1977.                 $rdvResult = new ArrayCollection();
  1978.             }
  1979.             foreach ($rdvs as $rdv) {
  1980.                 if ($rdv->getIdEtat()->getId() != 1) {
  1981.                     continue;
  1982.                 }
  1983.                 /** @var AudioMotif */
  1984.                 $audioMotif $this->getDoctrine()
  1985.                     ->getRepository(AudioMotif::class)
  1986.                     ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  1987.                 if (!$audioMotif) {
  1988.                     continue;
  1989.                 }
  1990.                 $duration '';
  1991.                 if (is_null($rdv->getDuration())) {
  1992.                     $duration $audioMotif->getDuration();
  1993.                 } else {
  1994.                     $duration $rdv->getDuration();
  1995.                 }
  1996.                 $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  1997.                 /** @var Rdv[] */
  1998.                 $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  1999.                     ->findAllReviewsCentre($rdvCentre->getId());
  2000.                 $rdvItem = [
  2001.                     "id" => $rdv->getId(),
  2002.                     "motif_id" => $rdv->getIdMotif()->getId(),
  2003.                     "duration" => $duration,
  2004.                     "color" => $audioMotif->getColor(),
  2005.                     "audio_id" => $rdv->getIdAudio()->getId(),
  2006.                     "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  2007.                     "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  2008.                     "client_id_temp" => $rdv->getIdClientTemp()->getId(),
  2009.                     "client_name" => $rdv->getIdClientTemp()->getName() . " " $rdv->getIdClientTemp()->getLastname(),
  2010.                     "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  2011.                     "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  2012.                     "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  2013.                     "testclient" => $rdv->getTestClient() ? [
  2014.                         "result" => $rdv->getTestClient()->getResultTonal(),
  2015.                         "date" => $rdv->getTestClient()->getDate(),
  2016.                         "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  2017.                     ] : null,
  2018.                     "name" => $rdvCentre->getName(),
  2019.                     "phone" => $rdvCentre->getPhone(),
  2020.                     "imgUrl" => $rdvCentre->getImgUrl(),
  2021.                     "address" => $rdvCentre->getAddress(),
  2022.                     "postale" => $rdvCentre->getPostale(),
  2023.                     "city" => $rdvCentre->getCity(),
  2024.                     "etat_id" => $rdvCentre->getId(),
  2025.                     "averageRating" => $publicFunction->calculateRating($centreRdvs),
  2026.                     "nbrReview" => count($centreRdvs),
  2027.                     "acceptedCurrency" => "CB Chèque",
  2028.                     "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  2029.                     "note" => $rdv->getNote(),
  2030.                     "comment" => $rdv->getComment(),
  2031.                     "review" => $rdv->getReview(),
  2032.                 ];
  2033.                 $rdvResult->add($rdvItem);
  2034.             }
  2035.         }
  2036.         if (count($rdvResult) > 0) {
  2037.             return new Response(json_encode(([
  2038.                 "rdv" => $rdvResult->toArray(),
  2039.                 "status" => 200,
  2040.             ])));
  2041.         } else {
  2042.             return new Response(json_encode(([
  2043.                 "message" => "Aucun rendez-vous n'a été trouvé!",
  2044.                 'path' => 'src/Controller/RdvController.php',
  2045.                 "status" => 404,
  2046.             ])));
  2047.         }
  2048.     }
  2049.     /**
  2050.      * @Route("/rdvs/old/clientTemp/{id}/centre", name="getOldRdvsByClientTempIdByCentre", methods={"GET","HEAD"})
  2051.      */
  2052.     public function getOldRdvsByClientTempIdByCentre(Request $requestClientTemp $clientTempPublicFunction $publicFunction)
  2053.     {
  2054.         if (!$request->query->get('token')) {
  2055.             return new Response(json_encode([
  2056.                 "message" => "Pas de token n'a été spécifié",
  2057.                 "status" => 401,
  2058.             ]), 401);
  2059.         }
  2060.         $entityManager $this->getDoctrine()->getManager();
  2061.         /** @var Token */
  2062.         $token $this->getDoctrine()
  2063.             ->getRepository(Token::class)
  2064.             ->findOneBy(['token' => $request->query->get('token')]);
  2065.         if (!$token) {
  2066.             return new Response(json_encode([
  2067.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2068.                 "status" => 404,
  2069.             ]), 404);
  2070.         }
  2071.         // get token age
  2072.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2073.         // if the token if older than 7 days
  2074.         if ($dateDiff->7) {
  2075.             $entityManager->remove($token);
  2076.             $entityManager->flush();
  2077.             return $this->json([
  2078.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2079.                 'path' => 'src/Controller/ClientController.php',
  2080.                 "status" => 401,
  2081.             ], 401);
  2082.         }
  2083.         $audioCentre $this->getDoctrine()
  2084.             ->getRepository(AudioCentre::class)
  2085.             ->findOneBy(['id_audio' => $token->getIdAudio()]);
  2086.         // we add the multi-centre so we wil desable the autorisation 
  2087.         /*
  2088.         if ($clientTemp->getIdCentre() != $audioCentre->getIdCentre()) {
  2089.             return new Response(json_encode([
  2090.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  2091.                 "status" => 404,
  2092.             ]), 404);
  2093.         }
  2094. */
  2095.         /** @var ActivityRepository */
  2096.         $activityRepo $this->getDoctrine()->getRepository(Rdv::class);
  2097.         if ($request->query->get('limit')) {
  2098.             /** @var Rdv[] */
  2099.             $rdvs $activityRepo
  2100.                 ->findLastsOldRdvsWithLimitTempByCentre($request->query->get('limit'), $clientTemp->getId(), $audioCentre->getIdCentre()->getId(), new DateTime());
  2101.             $rdvResult = new ArrayCollection();
  2102.         } else {
  2103.             /** @var Rdv[] */
  2104.             $rdvs $activityRepo
  2105.                 ->findOldRdvsTempByCentre($clientTemp->getId(), $audioCentre->getIdCentre()->getId(), new DateTime());
  2106.             $rdvResult = new ArrayCollection();
  2107.         }
  2108.         foreach ($rdvs as $rdv) {
  2109.             /*if ($rdv->getIdEtat()->getId() != 1) {
  2110.                 continue;
  2111.             }*/
  2112.             /** @var AudioMotif */
  2113.             $audioMotif $this->getDoctrine()
  2114.                 ->getRepository(AudioMotif::class)
  2115.                 ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  2116.             if (!$audioMotif) {
  2117.                 continue;
  2118.             }
  2119.             $duration '';
  2120.             if (is_null($rdv->getDuration())) {
  2121.                 $duration $audioMotif->getDuration();
  2122.             } else {
  2123.                 $duration $rdv->getDuration();
  2124.             }
  2125.             $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  2126.             /** @var Rdv[] */
  2127.             $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  2128.                 ->findAllReviewsCentre($rdvCentre->getId());
  2129.             $rdvItem = [
  2130.                 "id" => $rdv->getId(),
  2131.                 "motif_id" => $rdv->getIdMotif()->getId(),
  2132.                 "duration" => $duration,
  2133.                 "color" => $audioMotif->getColor(),
  2134.                 "audio_id" => $rdv->getIdAudio()->getId(),
  2135.                 "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  2136.                 "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  2137.                 "client_id_temp" => $rdv->getIdClientTemp()->getId(),
  2138.                 "client_name" => $rdv->getIdClientTemp()->getName() . " " $rdv->getIdClientTemp()->getLastname(),
  2139.                 "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  2140.                 "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  2141.                 "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  2142.                 "testclient" => $rdv->getTestClient() ? [
  2143.                     "result" => $rdv->getTestClient()->getResultTonal(),
  2144.                     "date" => $rdv->getTestClient()->getDate(),
  2145.                     "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  2146.                 ] : null,
  2147.                 "name" => $rdvCentre->getName(),
  2148.                 "phone" => $rdvCentre->getPhone(),
  2149.                 "imgUrl" => $rdvCentre->getImgUrl(),
  2150.                 "address" => $rdvCentre->getAddress(),
  2151.                 "postale" => $rdvCentre->getPostale(),
  2152.                 "city" => $rdvCentre->getCity(),
  2153.                 "etat_id" => $rdvCentre->getId(),
  2154.                 "averageRating" => $publicFunction->calculateRating($centreRdvs),
  2155.                 "nbrReview" => count($centreRdvs),
  2156.                 "acceptedCurrency" => "CB Chèque",
  2157.                 "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  2158.                 "note" => $rdv->getNote(),
  2159.                 "comment" => $rdv->getComment(),
  2160.                 "review" => $rdv->getReview(),
  2161.                 "status" => $rdv->getIdEtat()->getLibelle()
  2162.             ];
  2163.             $rdvResult->add($rdvItem);
  2164.         }
  2165.         if (count($rdvResult) > 0) {
  2166.             return new Response(json_encode(([
  2167.                 "rdv" => $rdvResult->toArray(),
  2168.                 "status" => 200,
  2169.             ])));
  2170.         } else {
  2171.             return new Response(json_encode(([
  2172.                 "message" => "Aucun rendez-vous n'a été trouvé!",
  2173.                 'path' => 'src/Controller/RdvController.php',
  2174.                 "status" => 404,
  2175.             ])));
  2176.         }
  2177.     }
  2178.     /**
  2179.      * @Route("/rdvs/clientTemp/{id}", name="getRdvsByClientTempID", methods={"GET","HEAD"})
  2180.      */
  2181.     public function getRdvsByClientTempID(Request $requestClientTemp $clientTempPublicFunction $publicFunction)
  2182.     {
  2183.         if (!$request->query->get('token')) {
  2184.             return new Response(json_encode([
  2185.                 "message" => "Pas de token n'a été spécifié",
  2186.                 "status" => 401,
  2187.             ]), 401);
  2188.         }
  2189.         $entityManager $this->getDoctrine()->getManager();
  2190.         /** @var Token */
  2191.         $token $this->getDoctrine()
  2192.             ->getRepository(Token::class)
  2193.             ->findOneBy(['token' => $request->query->get('token')]);
  2194.         if (!$token) {
  2195.             return new Response(json_encode([
  2196.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2197.                 "status" => 404,
  2198.             ]), 404);
  2199.         }
  2200.         // get token age
  2201.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2202.         // if the token if older than 7 days
  2203.         if ($dateDiff->7) {
  2204.             $entityManager->remove($token);
  2205.             $entityManager->flush();
  2206.             return $this->json([
  2207.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2208.                 'path' => 'src/Controller/ClientController.php',
  2209.                 "status" => 401,
  2210.             ], 401);
  2211.         }
  2212.         if ($clientTemp->getIdAudio() != $token->getIdAudio()) {
  2213.             return new Response(json_encode([
  2214.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  2215.                 "status" => 404,
  2216.             ]), 404);
  2217.         }
  2218.         /** @var Rdv[] */
  2219.         $rdvs $this->getDoctrine()
  2220.             ->getRepository(Rdv::class)
  2221.             ->findBy(['id_client_temp' => $clientTemp->getId(), 'id_audio' => $token->getIdAudio()]);
  2222.         $rdvResult = new ArrayCollection();
  2223.         if ($request->query->get('old')) {
  2224.             $oldRdvResult = new ArrayCollection();
  2225.         }
  2226.         foreach ($rdvs as $rdv) {
  2227.             if ($rdv->getIdEtat()->getId() != null) {
  2228.                 if ($rdv->getIdEtat()->getId() == 1) {
  2229.                     /** @var AudioMotif */
  2230.                     $audioMotif $this->getDoctrine()
  2231.                         ->getRepository(AudioMotif::class)
  2232.                         ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $token->getIdAudio()]);
  2233.                     /** @var Rdv[] */
  2234.                     $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  2235.                         ->findAllReviewsCentre($rdv->getIdCentre()->getId());
  2236.                     $duration '';
  2237.                     if (is_null($rdv->getDuration())) {
  2238.                         $duration $audioMotif->getDuration();
  2239.                     } else {
  2240.                         $duration $rdv->getDuration();
  2241.                     }
  2242.                     $rdvItem = [
  2243.                         "id" => $rdv->getId(),
  2244.                         "motif_id" => $rdv->getIdMotif()->getId(),
  2245.                         "duration" => $duration,
  2246.                         "color" => $audioMotif->getColor(),
  2247.                         "audio_id" => $rdv->getIdAudio()->getId(),
  2248.                         "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  2249.                         "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  2250.                         "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  2251.                         "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  2252.                         "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  2253.                         "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  2254.                         "client_name" => $rdv->getIdClientTemp()->getName() . " " $rdv->getIdClientTemp()->getLastname(),
  2255.                         "averageRating" => $publicFunction->calculateRating($centreRdvs),
  2256.                         "nbrReview" => count($centreRdvs),
  2257.                         "acceptedCurrency" => "CB Chèque",
  2258.                         "name" => $rdv->getIdCentre()->getName(),
  2259.                         "imgUrl" => $rdv->getIdCentre()->getImgUrl(),
  2260.                         "address" => $rdv->getIdCentre()->getAddress(),
  2261.                         "phone" => $rdv->getIdCentre()->getPhone(),
  2262.                         "etat_id" => $rdv->getIdEtat()->getId(),
  2263.                         "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  2264.                         "comment" => $rdv->getComment(),
  2265.                         "note" => $rdv->getNote(),
  2266.                         "review" => $rdv->getReview(),
  2267.                     ];
  2268.                     if ($rdv->getDate() >= new DateTime()) {
  2269.                         $rdvResult->add($rdvItem);
  2270.                     } else if ($request->query->get('old')) {
  2271.                         $oldRdvResult->add($rdvItem);
  2272.                     }
  2273.                 }
  2274.             }
  2275.         }
  2276.         if ($request->query->get('old')) {
  2277.             if (count($rdvResult) > || count($oldRdvResult) > 0) {
  2278.                 return new Response(json_encode(([
  2279.                     "rdv" => $rdvResult->toArray(),
  2280.                     "oldRdv" => $oldRdvResult->toArray(),
  2281.                     "status" => 200,
  2282.                 ])));
  2283.             } else {
  2284.                 return new Response(json_encode(([
  2285.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  2286.                     'path' => 'src/Controller/RdvController.php',
  2287.                     "status" => 404,
  2288.                 ])));
  2289.             }
  2290.         } else {
  2291.             if (count($rdvResult) > 0) {
  2292.                 return new Response(json_encode(([
  2293.                     "content" => $rdvResult->toArray(),
  2294.                     "status" => 200,
  2295.                 ])));
  2296.             } else {
  2297.                 return new Response(json_encode(([
  2298.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  2299.                     'path' => 'src/Controller/RdvController.php',
  2300.                     "status" => 404,
  2301.                 ])));
  2302.             }
  2303.         }
  2304.     }
  2305.     /**
  2306.      * @Route("/rdvs/clientTemp/{id}/centre", name="getRdvsByClientTempIDByCentre", methods={"GET","HEAD"})
  2307.      */
  2308.     public function getRdvsByClientTempIDByCentre(Request $requestClientTemp $clientTempPublicFunction $publicFunction)
  2309.     {
  2310.         if (!$request->query->get('token')) {
  2311.             return new Response(json_encode([
  2312.                 "message" => "Pas de token n'a été spécifié",
  2313.                 "status" => 401,
  2314.             ]), 401);
  2315.         }
  2316.         $entityManager $this->getDoctrine()->getManager();
  2317.         /** @var Token */
  2318.         $token $this->getDoctrine()
  2319.             ->getRepository(Token::class)
  2320.             ->findOneBy(['token' => $request->query->get('token')]);
  2321.         if (!$token) {
  2322.             return new Response(json_encode([
  2323.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2324.                 "status" => 404,
  2325.             ]), 404);
  2326.         }
  2327.         // get token age
  2328.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2329.         // if the token if older than 7 days
  2330.         if ($dateDiff->7) {
  2331.             $entityManager->remove($token);
  2332.             $entityManager->flush();
  2333.             return $this->json([
  2334.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2335.                 'path' => 'src/Controller/ClientController.php',
  2336.                 "status" => 401,
  2337.             ], 401);
  2338.         }
  2339.         $audioCentre $this->getDoctrine()
  2340.             ->getRepository(AudioCentre::class)
  2341.             ->findOneBy(['id_audio' => $token->getIdAudio()]);
  2342.         // we add the multi-centre so we wil desable the autorisation 
  2343.         /*    
  2344.         if ($clientTemp->getIdCentre() != $audioCentre->getIdCentre()) {
  2345.             return new Response(json_encode([
  2346.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  2347.                 "status" => 404,
  2348.             ]), 404);
  2349.         }*/
  2350.         /** @var Rdv[] */
  2351.         $rdvs $this->getDoctrine()
  2352.             ->getRepository(Rdv::class)
  2353.             ->findBy(['id_client_temp' => $clientTemp->getId(), 'id_centre' => $audioCentre->getIdCentre()]);
  2354.         $rdvResult = new ArrayCollection();
  2355.         if ($request->query->get('old')) {
  2356.             $oldRdvResult = new ArrayCollection();
  2357.         }
  2358.         foreach ($rdvs as $rdv) {
  2359.             if ($rdv->getIdEtat()->getId() != null) {
  2360.                 if ($rdv->getIdEtat()->getId() != 6) {
  2361.                     // if ($rdv->getIdEtat()->getId() == 1) {
  2362.                     /** @var AudioMotif */
  2363.                     $audioMotif $this->getDoctrine()
  2364.                         ->getRepository(AudioMotif::class)
  2365.                         ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  2366.                     /** @var Rdv[] */
  2367.                     $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  2368.                         ->findAllReviewsCentre($rdv->getIdCentre()->getId());
  2369.                     $duration '';
  2370.                     if (is_null($rdv->getDuration())) {
  2371.                         $duration $audioMotif->getDuration();
  2372.                     } else {
  2373.                         $duration $rdv->getDuration();
  2374.                     }
  2375.                     $rdvItem = [
  2376.                         "id" => $rdv->getId(),
  2377.                         "motif_id" => $rdv->getIdMotif()->getId(),
  2378.                         "duration" => $duration,
  2379.                         "color" => $audioMotif->getColor(),
  2380.                         "audio_id" => $rdv->getIdAudio()->getId(),
  2381.                         "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  2382.                         "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  2383.                         "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  2384.                         "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  2385.                         "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  2386.                         "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  2387.                         "client_name" => $rdv->getIdClientTemp()->getName() . " " $rdv->getIdClientTemp()->getLastname(),
  2388.                         "averageRating" => $publicFunction->calculateRating($centreRdvs),
  2389.                         "nbrReview" => count($centreRdvs),
  2390.                         "acceptedCurrency" => "CB Chèque",
  2391.                         "name" => $rdv->getIdCentre()->getName(),
  2392.                         "imgUrl" => $rdv->getIdCentre()->getImgUrl(),
  2393.                         "address" => $rdv->getIdCentre()->getAddress(),
  2394.                         "phone" => $rdv->getIdCentre()->getPhone(),
  2395.                         "etat_id" => $rdv->getIdEtat()->getId(),
  2396.                         "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  2397.                         "comment" => $rdv->getComment(),
  2398.                         "note" => $rdv->getNote(),
  2399.                         "review" => $rdv->getReview(),
  2400.                         "status" => $rdv->getIdEtat()->getLibelle()
  2401.                     ];
  2402.                     if ($rdv->getDate() >= new DateTime()) {
  2403.                         $rdvResult->add($rdvItem);
  2404.                     } else if ($request->query->get('old')) {
  2405.                         $oldRdvResult->add($rdvItem);
  2406.                     }
  2407.                 }
  2408.             }
  2409.         }
  2410.         if ($request->query->get('old')) {
  2411.             if (count($rdvResult) > || count($oldRdvResult) > 0) {
  2412.                 return new Response(json_encode(([
  2413.                     "rdv" => $rdvResult->toArray(),
  2414.                     "oldRdv" => $oldRdvResult->toArray(),
  2415.                     "status" => 200,
  2416.                 ])));
  2417.             } else {
  2418.                 return new Response(json_encode(([
  2419.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  2420.                     'path' => 'src/Controller/RdvController.php',
  2421.                     "status" => 404,
  2422.                 ])));
  2423.             }
  2424.         } else {
  2425.             if (count($rdvResult) > 0) {
  2426.                 return new Response(json_encode(([
  2427.                     "content" => $rdvResult->toArray(),
  2428.                     "status" => 200,
  2429.                 ])));
  2430.             } else {
  2431.                 return new Response(json_encode(([
  2432.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  2433.                     'path' => 'src/Controller/RdvController.php',
  2434.                     "status" => 404,
  2435.                 ])));
  2436.             }
  2437.         }
  2438.     }
  2439.     /**
  2440.      * @Route("/rdv", name="postRdv", methods={"POST"})
  2441.      */
  2442.     public function postRdv(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendarRdvSmsService $rdvSms): Response
  2443.     {
  2444.         $data json_decode($request->getContent(), true);
  2445.         if (!isset($data["token"])) {
  2446.             return new Response(json_encode([
  2447.                 "message" => "Pas de token n'a été spécifié",
  2448.                 "status" => 401,
  2449.             ]), 401);
  2450.         }
  2451.         $entityManager $this->getDoctrine()->getManager();
  2452.         /** @var Token */
  2453.         $token $this->getDoctrine()
  2454.             ->getRepository(Token::class)
  2455.             ->findOneBy(['token' => $data["token"]]);
  2456.         if (!$token) {
  2457.             return new Response(json_encode([
  2458.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2459.                 "status" => 404,
  2460.             ]), 404);
  2461.         }
  2462.         // get token age
  2463.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2464.         // if the token if older than 7 days
  2465.         if ($dateDiff->7) {
  2466.             $entityManager->remove($token);
  2467.             $entityManager->flush();
  2468.             return $this->json([
  2469.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2470.                 'path' => 'src/Controller/ClientController.php',
  2471.                 "status" => 401,
  2472.             ], 401);
  2473.         }
  2474.         // makes the rdv
  2475.         $rdv = new Rdv();
  2476.         if ($token->getIdAudio()) {
  2477.             //if the token if for an audio
  2478.             $audio $token->getIdAudio();
  2479.             if ((isset($data["client_id"]))) {
  2480.                 $client $this->getDoctrine()
  2481.                     ->getRepository(Client::class)
  2482.                     ->findOneBy(['id' => $data["client_id"]]);
  2483.             } else {
  2484.                 $client $this->getDoctrine()
  2485.                     ->getRepository(ClientTemp::class)
  2486.                     ->findOneBy(['id' => $data["client_id_temp"]]);
  2487.             }
  2488.             if ($client == null) {
  2489.                 return new Response(json_encode(([
  2490.                     'message' => 'Error, no client found at this id',
  2491.                     'path' => 'src/Controller/RdvController.php',
  2492.                     "status" => 400,
  2493.                 ])), 400);
  2494.             }
  2495.         } elseif ($token->getIdClient()) {
  2496.             //if the token if for a client
  2497.             $client $token->getIdClient();
  2498.             /** @var ActivityRepository */
  2499.             $activityRepo $this->getDoctrine();
  2500.             /** @var TestClient */
  2501.             $testClient $activityRepo
  2502.                 ->getRepository(TestClient::class)
  2503.                 ->getLatestTestClient($client);
  2504.             // add the test to the rdv if the client had one
  2505.             if ($testClient)
  2506.             // add the test to the rdv if the test isn't already on another rdv
  2507.             {
  2508.                 if (!$testClient->getRdv()) {
  2509.                     $rdv->setTestClient($testClient);
  2510.                 }
  2511.             }
  2512.             /** @var Audio */
  2513.             $audio $this->getDoctrine()
  2514.                 ->getRepository(Audio::class)
  2515.                 ->findOneBy(['id' => $data["audio_id"]]);
  2516.             if (isset($data["proche_id"])) {
  2517.                 $proche $this->getDoctrine()
  2518.                     ->getRepository(Proches::class)
  2519.                     ->findOneBy(['id' => $data["proche_id"], "id_client" => $client]);
  2520.             }
  2521.             if (!$audio) {
  2522.                 return new Response(json_encode(([
  2523.                     'message' => "Erreur, pas d'audio n'a été trouvé à cette id.",
  2524.                     'path' => 'src/Controller/RdvController.php',
  2525.                 ])), 400);
  2526.             }
  2527.             /** @var ClientBlocked */
  2528.             $clientBlocked $this->getDoctrine()
  2529.                 ->getRepository(ClientBlocked::class)
  2530.                 ->findOneBy(["id_audio" => $audio"id_client" => $client]);
  2531.             if ($clientBlocked) {
  2532.                 return new Response(json_encode(([
  2533.                     'message' => 'Erreur, vous avez été bloqué par cette audioprothésiste.',
  2534.                     'path' => 'src/Controller/RdvController.php',
  2535.                 ])), 400);
  2536.             }
  2537.             // set the rdv test
  2538.         } else {
  2539.             return new Response(json_encode(([
  2540.                 'message' => "Erreur, ce token n'est pas celui d'un client ou audioprothèsiste.",
  2541.                 'path' => 'src/Controller/RdvController.php',
  2542.             ])), 400);
  2543.         }
  2544.         $rdv->setIdAudio($audio);
  2545.         if (isset($proche)) {
  2546.             $rdv->setIdProche($proche);
  2547.         }
  2548.         if (isset($data["client_id_temp"])) {
  2549.             $rdv->setIdClientTemp($client);
  2550.         } else {
  2551.             $rdv->setIdClient($client);
  2552.         }
  2553.         if (isset($data["isMyaudio"])) {
  2554.             $rdv->setIsMyaudio(true);
  2555.         }
  2556.         if (isset($data["isRdvLead"])) {
  2557.             $rdv->setIsRdvLp(true);
  2558.         }
  2559.         if (isset($data["isRdvRapide"])) {
  2560.             $rdv->setIsRdvRapide(true);
  2561.         }
  2562.         if (isset($data["duree"])) {
  2563.             $rdv->setDuration($data["duree"]);
  2564.         }
  2565.         if (isset($data["color"])) {
  2566.             $rdv->setColor($data["color"]);
  2567.         }
  2568.         if (isset($data["lead"])) {
  2569.             $lead $this->getDoctrine()
  2570.                 ->getRepository(LeadRdv::class)
  2571.                 ->find($data["lead"]);
  2572.             $lead->setRdv($rdv);
  2573.             $leadStatus $this->entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'rdv_valider']);
  2574.             if ($leadStatus) {
  2575.                 $lead->setLeadStatus($leadStatus);
  2576.             }
  2577.         }
  2578.         /** @var Centre */
  2579.         if (isset($data["centre_id"])) {
  2580.             $centre $this->getDoctrine()
  2581.                 ->getRepository(Centre::class)
  2582.                 ->findOneBy(['id' => $data["centre_id"]]);
  2583.             if ($centre == null) {
  2584.                 return new Response(json_encode(([
  2585.                     'message' => 'Error, no centre found at this id',
  2586.                     'path' => 'src/Controller/RdvController.php',
  2587.                     "status" => 400,
  2588.                 ])), 400);
  2589.             }
  2590.             /** @var AudioCentre */
  2591.             $liaison $this->getDoctrine()
  2592.                 ->getRepository(AudioCentre::class)
  2593.                 ->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
  2594.             if ($liaison == null) {
  2595.                 return new Response(json_encode(([
  2596.                     'message' => 'Error, audio isnt part of the centre',
  2597.                     'path' => 'src/Controller/RdvController.php',
  2598.                     "status" => 400,
  2599.                 ])), 400);
  2600.             }
  2601.             $rdv->setIdCentre($centre);
  2602.         } elseif (isset($data["lieu_id"]) && $audio->getIsIndie()) {
  2603.             // tries to set the lieu if it's an audio indie
  2604.             $lieu $this->getDoctrine()
  2605.                 ->getRepository(Lieu::class)
  2606.                 ->findOneBy(['id' => $data["lieu_id"], 'id_gerant' => $data["audio_id"]]);
  2607.             if ($lieu == null) {
  2608.                 return new Response(json_encode(([
  2609.                     'message' => 'Error, no lieu found at this id',
  2610.                     'path' => 'src/Controller/RdvController.php',
  2611.                     "status" => 400,
  2612.                 ])), 400);
  2613.             }
  2614.             $rdv->setIdLieu($lieu);
  2615.         } else {
  2616.             return new Response(json_encode(([
  2617.                 'message' => 'Error, no lieu/centre id',
  2618.                 'path' => 'src/Controller/RdvController.php',
  2619.                 "status" => 400,
  2620.             ])), 400);
  2621.         }
  2622.         /** @var Motif */
  2623.         $motif $this->getDoctrine()
  2624.             ->getRepository(Motif::class)
  2625.             ->find($data["motif_id"]);
  2626.         if ($motif == null) {
  2627.             return new Response(json_encode(([
  2628.                 'message' => 'Error, no motif found at this id',
  2629.                 'path' => 'src/Controller/RdvController.php',
  2630.                 "status" => 400,
  2631.             ])), 400);
  2632.         }
  2633.         /** @var AudioMotif */
  2634.         $audioMotif $this->getDoctrine()
  2635.             ->getRepository(AudioMotif::class)
  2636.             ->findOneBy(["id_audio" => $audio->getId(), "id_motif" => $data["motif_id"]]);
  2637.         if ($audioMotif == null) {
  2638.             return new Response(json_encode(([
  2639.                 'message' => 'Error, no motif of this id found at this audio',
  2640.                 'path' => 'src/Controller/RdvController.php',
  2641.                 "status" => 400,
  2642.             ])), 400);
  2643.         }
  2644.         // remove the taken schedule by rdv to make sure there is no overlap
  2645.         $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  2646.         if (isset($data["note"])) {
  2647.             $rdv->setNote($data["note"]);
  2648.         }
  2649.         // test if the audio is available
  2650.         if ($audio->getIsIndie()) {
  2651.             if (isset($data["centre_id"])) {
  2652.                 if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  2653.                     return new Response(json_encode(([
  2654.                         'message' => 'Error, no horaire found for this audio',
  2655.                         'path' => 'src/Controller/RdvController.php',
  2656.                         "status" => 400,
  2657.                     ])), 400);
  2658.                 }
  2659.                 if ($publicFunction->calculScheduleFitDate($audio\DateTime::createFromFormat("d/m/Y H:i"$data["date"]), $audioMotif->getDuration(), $centre) == false) {
  2660.                     return new Response(json_encode(([
  2661.                         'message' => 'Error, no timestamp found at this time. Line n°' __LINE__,
  2662.                         'path' => 'src/Controller/RdvController.php',
  2663.                         "status" => 400,
  2664.                     ])), 400);
  2665.                 }
  2666.                 $remplacant_id $publicFunction->checkIfRemplacant($liaison->getHoraire(), $date);
  2667.             } else {
  2668.                 if ($lieu->getHoraire() == null || $lieu->getHoraire() == []) {
  2669.                     return new Response(json_encode(([
  2670.                         'message' => 'Error, no horaire found for this audio',
  2671.                         'path' => 'src/Controller/RdvController.php',
  2672.                         "status" => 400,
  2673.                     ])), 400);
  2674.                 }
  2675.                 if ($publicFunction->calculScheduleFitDate($audio\DateTime::createFromFormat("d/m/Y H:i"$data["date"]), $audioMotif->getDuration(), null$lieu) == false) {
  2676.                     return new Response(json_encode(([
  2677.                         'message' => 'Error, no timestamp found at this time. Line n°' __LINE__,
  2678.                         'path' => 'src/Controller/RdvController.php',
  2679.                         "status" => 400,
  2680.                     ])), 400);
  2681.                 }
  2682.                 $remplacant_id $publicFunction->checkIfRemplacant($lieu->getHoraire(), $date);
  2683.             }
  2684.         } else {
  2685.             if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  2686.                 return new Response(json_encode(([
  2687.                     'message' => 'Error, no horaire found for this audio',
  2688.                     'path' => 'src/Controller/RdvController.php',
  2689.                     "status" => 400,
  2690.                 ])), 400);
  2691.             }
  2692.             /*  if (!$publicFunction->calculScheduleFitDate($audio, \DateTime::createFromFormat("d/m/Y H:i", $data["date"]), $audioMotif->getDuration(), $centre))
  2693.                 return new Response(json_encode(([
  2694.                     'message' => "Error, no timestamp found at this time. Motif size: {$audioMotif->getDuration()} Line n°" . __LINE__,
  2695.                     'path' => 'src/Controller/RdvController.php',
  2696.                     "status" => 400,
  2697.                 ])), 400);*/
  2698.             $remplacant_id $publicFunction->checkIfRemplacant($liaison->getHoraire(), \DateTime::createFromFormat("d/m/Y H:i"$data["date"]));
  2699.         }
  2700.         $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  2701.         $existingRdv $this->getDoctrine()
  2702.             ->getRepository(Rdv::class)
  2703.             ->findOneBy([
  2704.                 'date' => $date,
  2705.                 'id_audio' => $audio,
  2706.                 'id_centre' => $rdv->getIdCentre() ?? null,
  2707.                 'id_lieu' => $rdv->getIdLieu()   ?? null,
  2708.             ]);
  2709.         if ($existingRdv) {
  2710.             return new Response(json_encode([
  2711.                 'message' => 'Un rendez-vous est déjà pris pour cette date et ce créneau.',
  2712.                 'status' => 400,
  2713.             ]), 400);
  2714.         }
  2715.         $rdv->setDate($date);
  2716.         $rdv->setDateCreation(\DateTime::createFromFormat("d/m/Y H:i"date('d/m/Y H:i')));
  2717.         /** @var EtatRdv */
  2718.         $etat $this->getDoctrine()
  2719.             ->getRepository(EtatRdv::class)
  2720.             ->findOneBy(['id' => $data["etat_id"]]);
  2721.         if ($etat == null) {
  2722.             return new Response(json_encode(([
  2723.                 'message' => 'Error, no etat found at this id',
  2724.                 'path' => 'src/Controller/RdvController.php',
  2725.                 "status" => 400,
  2726.             ])), 400);
  2727.         }
  2728.         $rdv->setIdEtat($etat);
  2729.         $rdv->setIdMotif($motif);
  2730.         $rdv->setIsAbsence(0);
  2731.         $rdv->setCacher(0);
  2732.         if ($remplacant_id != -1) {
  2733.             $remplacant $this->getDoctrine()
  2734.                 ->getRepository(Remplacant::class)
  2735.                 ->find($remplacant_id);
  2736.             $rdv->setRemplacant($remplacant);
  2737.         }
  2738.         $entityManager $this->getDoctrine()->getManager();
  2739.         $entityManager->persist($rdv);
  2740.         $entityManager->flush();
  2741.         /// SMSEMAIL A décommenter pour autoriser l'envoi de sms / email à la création de rdv par l'audio / le client SMSEMAIL ///
  2742.         $date $rdv->getDate();
  2743.         $smsDate $date->format('d-m-Y H:i');
  2744.         $locale 'fr_FR';
  2745.         $formatter = new IntlDateFormatter(
  2746.             $locale,
  2747.             IntlDateFormatter::FULL,
  2748.             IntlDateFormatter::SHORT,
  2749.             null,
  2750.             IntlDateFormatter::GREGORIAN,
  2751.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  2752.         );
  2753.         $smsDateLongFormat $formatter->format($date);
  2754.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  2755.         $client->setIdCentre($rdv->getIdCentre());
  2756.         $client->setIdAudio($rdv->getIdAudio());
  2757.         $entityManager->persist($client);
  2758.         $entityManager->flush();
  2759.         // client notif mail Sms
  2760.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  2761.         $frenchDate ucfirst($frenchDate);
  2762.         $responses = [
  2763.             'rangeAge' => isset($data['rangeAge']) ? $data['rangeAge'] : null,
  2764.             'situations' => (isset($data['situations']) && !empty($data['situations'])) ? implode(", "$data['situations']) : null,
  2765.             'equipeAppareil' => isset($data['equipe']) ? $data['equipe'] : null,
  2766.             'durationEquipe' => isset($data['durationEquipe']) ? $data['durationEquipe'] : null,
  2767.             'bilanAuditif' => isset($data['bilanAuditif']) ? $data['bilanAuditif'] : null,
  2768.             'ordonance' => isset($data['ordonnance']) ? $data['ordonnance'] : null,
  2769.             'dateOrdonance' => isset($data['dateOrdonance']) ? $data['dateOrdonance'] : null,
  2770.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  2771.         ];
  2772.         $paramsSourceLead = [
  2773.             'trafficSource' => isset($data['traffic_source']) ? $data['traffic_source'] : null,
  2774.             'articleName' => isset($data['article_name']) ? $data['article_name'] : null,
  2775.             'lpVersion' => isset($data['lp_version']) ? $data['lp_version'] : null,
  2776.         ];
  2777.         $params = array(
  2778.             "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  2779.             "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  2780.             "date" => $smsDateLongFormat,
  2781.             "RdvDate" => $smsDateLongFormat,
  2782.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  2783.             "centerName" => $rdv->getIdCentre()->getName(),
  2784.             "prenom" => $client->getName(),
  2785.             "centerAddress" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  2786.             "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  2787.             'motif' => $rdv->getIdMotif()->getTitre(),
  2788.             "centerCity" => $rdv->getIdCentre()->getCity(),
  2789.             "audioName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  2790.             'titre' => "Votre rendez-vous est validé le " substr($smsDate010) . " à "  substr($smsDate1115),
  2791.             "position" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  2792.             "address" => $rdv->getIdCentre()->getAddress(),
  2793.             "postal" => $rdv->getIdCentre()->getPostale(),
  2794.             "city" => $rdv->getIdCentre()->getCity(),
  2795.             "clientEmail" => $client->getMail(),
  2796.             "clientPassword" => isset($data["passwordGenerated"]) ? $data["passwordGenerated"] : null,
  2797.             "clientAddress" => $client->getAddress(),
  2798.             "clientPostal" => $client->getPostal(),
  2799.             "clientCity" => $client->getCity(),
  2800.             "audioName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  2801.             "frenchDate" => $frenchDate,
  2802.             "heure" => substr($smsDate1115),
  2803.             "centerName" => $rdv->getIdCentre()->getName(),
  2804.             "audioMail" => $rdv->getIdAudio()->getMail(),
  2805.             "modifUrl" => "{$_ENV['BASE_client']}mes-rendez-vous",
  2806.         );
  2807.         $paramsPatient $params;
  2808.         $isNew false;
  2809.         if (isset($data["isLead"]) && isset($data["passwordGenerated"]) != null) {
  2810.             $subject "✅Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  2811.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject189);
  2812.             $isNew true;
  2813.         } else {
  2814.             $subject "Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  2815.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject181);
  2816.         }
  2817.         $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.";
  2818.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  2819.         // audio Notif mail SMS
  2820.         $birthday $rdv->getIdClient()->getBirthdate();
  2821.         $params = array(
  2822.             "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  2823.             "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  2824.             "date" => substr($smsDate010),
  2825.             "heure" => substr($smsDate1115),
  2826.             "mail" => $client->getMail(),
  2827.             "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  2828.             'telClient' => $client->getPhone(),
  2829.             'phone' => $client->getPhone(),
  2830.             'clientCivilite' => $client->getCivilite(),
  2831.             'clientNom' => $client->getLastname(),
  2832.             'clientPrenom' => $client->getName(),
  2833.             'clientPostal' => $client->getPostal(),
  2834.             'clientMail' => $client->getMail(),
  2835.             'clientPhone' => $client->getPhone(),
  2836.             'motif' => $rdv->getIdMotif()->getTitre(),
  2837.             'birthdate' => $client->getBirthdate() ? $client->getBirthdate()->format("d/m/Y") : null,
  2838.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  2839.             'centerName' => $rdv->getIdCentre()->getName(),
  2840.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  2841.             'centerCity' => $rdv->getIdCentre()->getCity(),
  2842.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  2843.             'idPatient' => $client->getId(),
  2844.             'proUrl' => "{$_ENV['BASE_logiciel']}",
  2845.             'frenchDate' => $frenchDate,
  2846.             'responses' => $responses,
  2847.         );
  2848.         $templateEmail 182;
  2849.         if (!empty($data['canMove'])) {
  2850.             $templateEmail 197;
  2851.         }
  2852.         $subject "✅Nouveau Rendez-vous My Audio le " $frenchDate " à " substr($smsDate1115);
  2853.         $publicFunction->sendEmail($params$rdv->getIdAudio()->getMail(), $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject$templateEmail);
  2854.         $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.";
  2855.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$rdv->getIdAudio()->getPhone());
  2856.         // send notif to admin
  2857.         $paramsAdmin = array(
  2858.             "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  2859.             "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  2860.             "RdvDate" => substr($smsDate010),
  2861.             "heure" => substr($smsDate1115),
  2862.             "clientMail" => $client->getMail(),
  2863.             "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  2864.             'telClient' => $client->getPhone(),
  2865.             'clientNom' => $client->getLastname(),
  2866.             'clientPrenom' => $client->getName(),
  2867.             'clientCivilite' => $client->getCivilite(),
  2868.             'clientPostal' => $client->getPostal(),
  2869.             'clientPhone' => $client->getPhone(),
  2870.             'motif' => $rdv->getIdMotif()->getTitre(),
  2871.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  2872.             'centerName' => $rdv->getIdCentre()->getName(),
  2873.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  2874.             'centerCity' => $rdv->getIdCentre()->getCity(),
  2875.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  2876.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  2877.             'date' => substr($smsDate010),
  2878.             'urlApi' => "{$_ENV['BASE_API']}",
  2879.             'clientId' => $client->getId(),
  2880.             'centerId' => $rdv->getIdCentre()->getId(),
  2881.             'frenchDate' => $frenchDate,
  2882.             'responses' => $responses,
  2883.             'paramsSourceLead' => $paramsSourceLead
  2884.         );
  2885.         $subject "Nouveau RDV MA | RR - " $rdv->getIdCentre()->getName();
  2886.         $templateEmail 183;
  2887.         if (!empty($data['canMove'])) {
  2888.             $templateEmail 190;
  2889.         }
  2890.         if (!isset($data["isLead"])) {
  2891.             $publicFunction->sendEmail($paramsAdmin"lead.myaudio@gmail.com""my audio"$subject$templateEmail);
  2892.         }
  2893.         //$publicFunction->sendEmail($paramsAdmin,"testpation1254@yopmail.com","my audio", 'Nouveau RDV à My Audio Pro', $templateEmail);
  2894.         $publicFunction->sendEmail($paramsAdmin"mickael.aubard@myaudio.fr""my audio"$subject$templateEmail);
  2895.         $publicFunction->sendEmail($paramsAdmin"mickael@aubard.me""my audio"$subject$templateEmail);
  2896.         // google calendar post
  2897.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  2898.             ->findBy(array('audio' => $audio->getId()));
  2899.         $data['rdv'] = $rdv->getId();
  2900.         if (isset($data['clientRdvLp']) && !empty($data['clientRdvLp'])) {
  2901.             $rdvLead $this->entityManager->getRepository(LeadRdv::class)->find($data['clientRdvLp']);
  2902.             if ($rdvLead) {
  2903.                 $leadStatus $this->entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'rdv_valider']);
  2904.                 if ($leadStatus) {
  2905.                     $rdvLead->setLeadStatus($leadStatus);
  2906.                     $rdvLead->setRdv($rdv);
  2907.                     $this->entityManager->flush();
  2908.                 }
  2909.             }
  2910.         }
  2911.         foreach ($synchronisations as $synchronisation) {
  2912.             if (!$synchronisation->getIsDeleted()) {
  2913.                 $googleCalendar->checkAndRefreshAccessToken($synchronisation);
  2914.                 $googleCalendar->createEvent($synchronisation$data);
  2915.             }
  2916.         }
  2917.         return new Response(json_encode(([
  2918.             "id" => $rdv->getId(),
  2919.             "motif_id" => $rdv->getIdMotif()->getId(),
  2920.             "audio_id" => $rdv->getIdAudio()->getId(),
  2921.             "remplacant_id" => $remplacant_id == -null $remplacant_id,
  2922.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  2923.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  2924.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  2925.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  2926.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  2927.             "testclient" => $rdv->getTestClient() ? [
  2928.                 "result" => $rdv->getTestClient()->getResultTonal(),
  2929.                 "date" => $rdv->getTestClient()->getDate(),
  2930.                 "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  2931.             ] : null,
  2932.             "duration" => $audioMotif->getDuration(),
  2933.             "consigne" => $audioMotif->getConsigne(),
  2934.             "etat_id" => $rdv->getIdEtat()->getId(),
  2935.             "date" => $rdv->getDate(),
  2936.             "comment" => $rdv->getComment(),
  2937.             "centerName" => $rdv->getIdCentre()->getName(),
  2938.             "review" => $rdv->getReview(),
  2939.             "note" => $rdv->getNote(),
  2940.             "status" => 200,
  2941.             "paramsPatient" => $paramsPatient,
  2942.             "isNew" => $isNew,
  2943.         ])));
  2944.     }
  2945.     /**
  2946.      * @Route("/rdv/{id}/trusteduser", name="contactTrustedUser", methods={"POST"})
  2947.      */
  2948.     public function contactTrustedUser(Request $requestPublicFunction $publicFunction)
  2949.     {
  2950.         $pastDate $rdv->getDate();
  2951.         $data json_decode($request->getContent(), true);
  2952.         $entityManager $this->getDoctrine()->getManager();
  2953.         if (!isset($data["token"])) {
  2954.             return new Response(json_encode([
  2955.                 "message" => "Pas de token n'a été spécifié",
  2956.                 "status" => 401,
  2957.             ]), 401);
  2958.         }
  2959.         /** @var Token */
  2960.         $token $this->getDoctrine()
  2961.             ->getRepository(Token::class)
  2962.             ->findOneBy(['token' => $data["token"]]);
  2963.         if (!$token) {
  2964.             return new Response(json_encode([
  2965.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2966.                 "status" => 404,
  2967.             ]), 404);
  2968.         }
  2969.         // get token age
  2970.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2971.         // if the token if older than 7 days
  2972.         if ($dateDiff->7) {
  2973.             $entityManager->remove($token);
  2974.             $entityManager->flush();
  2975.             return $this->json([
  2976.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2977.                 'path' => 'src/Controller/ClientController.php',
  2978.                 "status" => 401,
  2979.             ], 401);
  2980.         }
  2981.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  2982.             return new Response(json_encode([
  2983.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  2984.                 "status" => 404,
  2985.             ]), 404);
  2986.         }
  2987.         if (isset($data["date"])) {
  2988.             // remove the taken schedule by rdv to make sure there is no overlap
  2989.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  2990.             $audioMotif $this->getDoctrine()
  2991.                 ->getRepository(AudioMotif::class)
  2992.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  2993.             if ($audioMotif == null) {
  2994.                 return new Response(json_encode(([
  2995.                     'message' => 'Error, no motif of this id found at this audio',
  2996.                     'path' => 'src/Controller/RdvController.php',
  2997.                     "status" => 400,
  2998.                 ])), 400);
  2999.             }
  3000.             if ($rdv->getIdAudio()->getIsIndie()) {
  3001.                 if ($rdv->getIdCentre()) {
  3002.                     // regular centre audio indie
  3003.                     /** @var AudioCentre */
  3004.                     $liaison $this->getDoctrine()
  3005.                         ->getRepository(AudioCentre::class)
  3006.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  3007.                     if ($liaison == null) {
  3008.                         return new Response(json_encode(([
  3009.                             'message' => 'Error, audio isnt part of the centre',
  3010.                             'path' => 'src/Controller/RdvController.php',
  3011.                             "status" => 400,
  3012.                         ])), 400);
  3013.                     }
  3014.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  3015.                         return new Response(json_encode(([
  3016.                             'message' => 'Error, no horaire found for this audio',
  3017.                             'path' => 'src/Controller/RdvController.php',
  3018.                             "status" => 400,
  3019.                         ])), 400);
  3020.                     }
  3021.                     // if ($publicFunction->calculScheduleFitDate($liaison->getHoraire(), $rdv->getIdAudio(), $date, $audioMotif->getDuration(), $rdv->getIdCentre()) == false) {
  3022.                     //     return new Response(json_encode(([
  3023.                     //         'message' => 'Error, no timestamp found at this time',
  3024.                     //         'path' => 'src/Controller/RdvController.php',
  3025.                     //         "status" => 400,
  3026.                     //     ])),400);
  3027.                     // }
  3028.                 } else {
  3029.                     // lieu audio indie
  3030.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  3031.                         return new Response(json_encode(([
  3032.                             'message' => 'Error, no horaire found for this audio',
  3033.                             'path' => 'src/Controller/RdvController.php',
  3034.                             "status" => 400,
  3035.                         ])), 400);
  3036.                     }
  3037.                     // if ($publicFunction->calculScheduleFitDate($rdv->getIdLieu()->getHoraire(), $rdv->getIdAudio(), $date, $audioMotif->getDuration(), null, $rdv->getIdLieu()) == false) {
  3038.                     //     return new Response(json_encode(([
  3039.                     //         'message' => 'Error, no timestamp found at this time',
  3040.                     //         'path' => 'src/Controller/RdvController.php',
  3041.                     //         "status" => 400,
  3042.                     //     ])),400);
  3043.                     // }
  3044.                 }
  3045.             } else {
  3046.                 // regular centre
  3047.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  3048.                     return new Response(json_encode(([
  3049.                         'message' => 'Error, no horaire found for this audio',
  3050.                         'path' => 'src/Controller/RdvController.php',
  3051.                         "status" => 400,
  3052.                     ])), 400);
  3053.                 }
  3054.                 // if ($publicFunction->calculScheduleFitDate($rdv->getIdCentre()->getHoraire(), $rdv->getIdAudio(), $date, $audioMotif->getDuration(), $rdv->getIdCentre()) == false) {
  3055.                 //     return new Response(json_encode(([
  3056.                 //         'message' => 'Error, no timestamp found at this time',
  3057.                 //         'path' => 'src/Controller/RdvController.php',
  3058.                 //         "status" => 400,
  3059.                 //     ])),400);
  3060.                 // }
  3061.             }
  3062.             $rdv->setDate($date);
  3063.         }
  3064.         $date $rdv->getDate();
  3065.         $smsDate $date->format('d-m-Y H:i');
  3066.         $oldDate $pastDate->format('d-m-Y H:i');
  3067.         $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>");
  3068.         return new Response(json_encode(([
  3069.             "id" => $rdv->getId(),
  3070.             "status" => 200,
  3071.         ])));
  3072.     }
  3073.     /**
  3074.      * @Route("/rdv/{id}", name="editRdvByID", methods={"PUT"})
  3075.      */
  3076.     public function editRdvByID(PublicFunction $publicFunctionRdv $rdvRequest $requestGoogleCalendarService $googleCalendarRdvSmsService $rdvSms): Response
  3077.     {
  3078.         $pastDate $rdv->getDate();
  3079.         $pastDuration $rdv->getDuration();
  3080.         $data json_decode($request->getContent(), true);
  3081.         $entityManager $this->getDoctrine()->getManager();
  3082.         if (!isset($data["token"])) {
  3083.             return new Response(json_encode([
  3084.                 "message" => "Pas de token n'a été spécifié",
  3085.                 "status" => 401,
  3086.             ]), 401);
  3087.         }
  3088.         /** @var Token */
  3089.         $token $this->getDoctrine()
  3090.             ->getRepository(Token::class)
  3091.             ->findOneBy(['token' => $data["token"]]);
  3092.         if (!$token) {
  3093.             return new Response(json_encode([
  3094.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  3095.                 "status" => 404,
  3096.             ]), 404);
  3097.         }
  3098.         // get token age
  3099.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  3100.         // if the token if older than 7 days
  3101.         if ($dateDiff->7) {
  3102.             $entityManager->remove($token);
  3103.             $entityManager->flush();
  3104.             return $this->json([
  3105.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  3106.                 'path' => 'src/Controller/ClientController.php',
  3107.                 "status" => 401,
  3108.             ], 401);
  3109.         }
  3110.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  3111.             return new Response(json_encode([
  3112.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  3113.                 "status" => 404,
  3114.             ]), 404);
  3115.         }
  3116.         if (isset($data["etat_id"])) {
  3117.             $etat $this->getDoctrine()
  3118.                 ->getRepository(EtatRdv::class)
  3119.                 ->findOneBy(['id' => $data["etat_id"]]);
  3120.             if ($etat == null) {
  3121.                 return new Response(json_encode(([
  3122.                     'message' => 'Error, no etat found at this id',
  3123.                     'path' => 'src/Controller/TrustedUserController.php',
  3124.                     "status" => 400,
  3125.                 ])), 400);
  3126.             }
  3127.             $rdv->setIdEtat($etat);
  3128.         }
  3129.         if (isset($data["audio_id"])) {
  3130.             $audio $this->getDoctrine()
  3131.                 ->getRepository(Audio::class)
  3132.                 ->findOneBy(['id' => $data["audio_id"]]);
  3133.             if ($audio == null) {
  3134.                 return new Response(json_encode(([
  3135.                     'message' => 'Error, no audio found at this id',
  3136.                     'path' => 'src/Controller/TrustedUserController.php',
  3137.                     "status" => 400,
  3138.                 ])), 400);
  3139.             }
  3140.             $rdv->setIdAudio($audio);
  3141.         }
  3142.         if (isset($data["motif_id"])) {
  3143.             $motif $this->getDoctrine()
  3144.                 ->getRepository(Motif::class)
  3145.                 ->find($data["motif_id"]);
  3146.             if ($motif == null) {
  3147.                 return new Response(json_encode(([
  3148.                     'message' => 'Error, no motif found at this id',
  3149.                     'path' => 'src/Controller/TrustedUserController.php',
  3150.                     "status" => 400,
  3151.                 ])), 400);
  3152.             }
  3153.             $rdv->setIdMotif($motif);
  3154.         }
  3155.         if (isset($data["client_id"])) {
  3156.             $client $this->getDoctrine()
  3157.                 ->getRepository(Client::class)
  3158.                 ->findOneBy(['id' => $data["client_id"]]);
  3159.             if ($client == null) {
  3160.                 return new Response(json_encode(([
  3161.                     'message' => 'Error, no client found at this id',
  3162.                     'path' => 'src/Controller/TrustedUserController.php',
  3163.                     "status" => 400,
  3164.                 ])), 400);
  3165.             }
  3166.             $rdv->setIdClient($client);
  3167.         }
  3168.         // set client status
  3169.         if (isset($data["client_status_id"])) {
  3170.             $status $this->getDoctrine()
  3171.                 ->getRepository(ClientStatus::class)
  3172.                 ->findOneBy(['id' => $data["client_status_id"]]);
  3173.             if ($status == null) {
  3174.                 return new Response(json_encode(([
  3175.                     'message' => 'Error, no status found at this id',
  3176.                     'path' => 'src/Controller/TrustedUserController.php',
  3177.                     "status" => 400,
  3178.                 ])), 400);
  3179.             }
  3180.             $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  3181.             $client->setClientStatus($status);
  3182.             $client->setLastUpdateStatus(new \DateTimeImmutable);
  3183.         }
  3184.         if (isset($data["date"])) {
  3185.             // remove the taken schedule by rdv to make sure there is no overlap
  3186.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  3187.             $dateInput \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  3188.             $audioMotif $this->getDoctrine()
  3189.                 ->getRepository(AudioMotif::class)
  3190.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  3191.             if ($audioMotif == null) {
  3192.                 return new Response(json_encode(([
  3193.                     'message' => 'Error, no motif of this id found at this audio',
  3194.                     'path' => 'src/Controller/RdvController.php',
  3195.                     "status" => 400,
  3196.                 ])), 400);
  3197.             }
  3198.             if ($rdv->getIdAudio()->getIsIndie()) {
  3199.                 if ($rdv->getIdCentre()) {
  3200.                     // regular centre audio indie
  3201.                     /** @var AudioCentre */
  3202.                     $liaison $this->getDoctrine()
  3203.                         ->getRepository(AudioCentre::class)
  3204.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  3205.                     if ($liaison == null) {
  3206.                         return new Response(json_encode(([
  3207.                             'message' => 'Error, audio isnt part of the centre',
  3208.                             'path' => 'src/Controller/RdvController.php',
  3209.                             "status" => 400,
  3210.                         ])), 400);
  3211.                     }
  3212.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  3213.                         return new Response(json_encode(([
  3214.                             'message' => 'Error, no horaire found for this audio',
  3215.                             'path' => 'src/Controller/RdvController.php',
  3216.                             "status" => 400,
  3217.                         ])), 400);
  3218.                     }
  3219.                 } else {
  3220.                     // lieu audio indie
  3221.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  3222.                         return new Response(json_encode(([
  3223.                             'message' => 'Error, no horaire found for this audio',
  3224.                             'path' => 'src/Controller/RdvController.php',
  3225.                             "status" => 400,
  3226.                         ])), 400);
  3227.                     }
  3228.                 }
  3229.             } else {
  3230.                 // regular centre
  3231.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  3232.                     return new Response(json_encode(([
  3233.                         'message' => 'Error, no horaire found for this audio',
  3234.                         'path' => 'src/Controller/RdvController.php',
  3235.                         "status" => 400,
  3236.                     ])), 400);
  3237.                 }
  3238.             }
  3239.             $rdv->setDate($date);
  3240.         }
  3241.         if (isset($data["comment"]) && $token->getIdClient()) {
  3242.             $rdv->setComment($data["comment"]);
  3243.         }
  3244.         if (isset($data["review"]) && $token->getIdClient()) {
  3245.             $rdv->setReview($data["review"]);
  3246.         }
  3247.         if (isset($data["note"])) {
  3248.             $rdv->setNote($data["note"]);
  3249.         }
  3250.         if (isset($data["duree"])) {
  3251.             $rdv->setDuration($data["duree"]);
  3252.         }
  3253.         ////// SMSEMAIL A décommenter pour activer l'envoi de SMS + MAIL pour modification annulation de RDV, coté audio / client SMSEMAIL ////
  3254.         $date $rdv->getDate();
  3255.         $smsDate $date->format('d-m-Y H:i');
  3256.         $oldDate $pastDate->format('d-m-Y H:i');
  3257.         $locale 'fr_FR';
  3258.         $formatter = new IntlDateFormatter(
  3259.             $locale,
  3260.             IntlDateFormatter::FULL,
  3261.             IntlDateFormatter::SHORT,
  3262.             null,
  3263.             IntlDateFormatter::GREGORIAN,
  3264.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  3265.         );
  3266.         $smsDateLongFormat $formatter->format($date);
  3267.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  3268.         $frenchDate ucfirst($frenchDate);
  3269.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  3270.         // notif client
  3271.         if ($rdv->getIdEtat()->getId() != 2) {
  3272.             if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  3273.                 if ($data["sms"]) {
  3274.                     $params = array(
  3275.                         "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  3276.                         "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  3277.                         "date" => $smsDateLongFormat,
  3278.                         "heure" => substr($smsDate1115),
  3279.                         "motif" => $rdv->getIdMotif()->getTitre(),
  3280.                         "centerName" => $rdv->getIdCentre()->getName(),
  3281.                         "centerAddress" => $rdv->getIdCentre()->getAddress(),
  3282.                         "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  3283.                         "audioMail" => $rdv->getIdAudio()->getMail(),
  3284.                         "centerPhone" => $rdv->getIdCentre()->getPhone(),
  3285.                         "centerCity" => $rdv->getIdCentre()->getCity(),
  3286.                         "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  3287.                         'titre' => 'Votre rendez-vous est modifié pour le',
  3288.                         'frenchDate' => $frenchDate,
  3289.                     );
  3290.                     $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  3291.                     $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject184);
  3292.                     $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.";
  3293.                     $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  3294.                 }
  3295.             }
  3296.         }
  3297.         //     //// == suppression
  3298.         else if ($rdv->getIdEtat()->getId() == 2) {
  3299.             // delete google agenda event
  3300.             $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  3301.                 ->findBy(array('rdv' => $rdv));
  3302.             foreach ($rdvEvents as $rdvEvent) {
  3303.                 $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  3304.                 if ($googleCalendar) {
  3305.                     $googleCalendar->deleteEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId());
  3306.                     $entityManager->remove($rdvEvent);
  3307.                     $entityManager->flush();
  3308.                 }
  3309.             }
  3310.             //if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  3311.             //if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {                   
  3312.             $params = array(
  3313.                 "date" => substr($smsDate010),
  3314.                 "lien" => "{$_ENV['BASE_client']}search",
  3315.                 "heure" => substr($smsDate1115),
  3316.                 "patientName" => $client->getLastName(),
  3317.                 'titre' => 'Votre rendez-vous est annulé :',
  3318.                 'centerName' => $rdv->getIdCentre()->getName(),
  3319.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  3320.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  3321.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  3322.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  3323.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  3324.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  3325.                 'motif' => $rdv->getIdMotif()->getTitre(),
  3326.             );
  3327.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  3328.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject188);
  3329.             if ($data["sms"]) {
  3330.                 $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  3331.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  3332.             }
  3333.             //}
  3334.         }
  3335.         // set center
  3336.         if (isset($data["centre_id"])) {
  3337.             $entityManager $this->getDoctrine()->getManager();
  3338.             $centreId $data["centre_id"];
  3339.             $centre $entityManager->getRepository(Centre::class)->find($centreId);
  3340.             if (!$centre) {
  3341.                 return $this->json([
  3342.                     'message' => 'Error, no Centre found with this ID',
  3343.                     'path' => 'src/Controller/YourController.php',
  3344.                 ]);
  3345.             }
  3346.             $rdv->setIdCentre($centre);
  3347.         }
  3348.         $rdv->setGoogleAgendaImported(false);
  3349.         //notif Audio
  3350.         if ($rdv->getIdEtat()->getId() != 2) {
  3351.             if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  3352.                 if ($data["sms"]) {
  3353.                     $params = array(
  3354.                         "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  3355.                         "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  3356.                         "date" => substr($smsDate010),
  3357.                         "frenchDate" => $frenchDate,
  3358.                         "heure" => substr($smsDate1115),
  3359.                         'motif' => $rdv->getIdMotif()->getTitre(),
  3360.                         'clientPhone' => $client->getPhone(),
  3361.                         'clientNom' => $client->getLastname(),
  3362.                         'clientPrenom' => $client->getName(),
  3363.                         'clientCivilite' => $client->getCivilite(),
  3364.                         'clientPostal' => $client->getPostal(),
  3365.                         'clientMail' => $client->getMail(),
  3366.                         'centerName' => $rdv->getIdCentre()->getName(),
  3367.                         'centerPostal' => $rdv->getIdCentre()->getPostale(),
  3368.                         'centerCity' => $rdv->getIdCentre()->getCity(),
  3369.                         'centerAddress' => $rdv->getIdCentre()->getAddress(),
  3370.                         'idPatient' => $client->getId(),
  3371.                         'proUrl' => "{$_ENV['BASE_logiciel']}",
  3372.                         'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  3373.                         'titre' => 'Votre rendez-vous est modifié pour le :'
  3374.                     );
  3375.                     $subject "🔀 Rendez-vous My Audio modifié du " $frenchDate " à " substr($smsDate1115);
  3376.                     $publicFunction->sendEmail($params$rdv->getIdAudio()->getMail(), $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject186);
  3377.                     $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.";
  3378.                     $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$rdv->getIdAudio()->getPhone());
  3379.                 }
  3380.             }
  3381.         } else if ($rdv->getIdEtat()->getId() == 2) {
  3382.             if ($data["sms"]) {
  3383.                 $params = array(
  3384.                     "date" => substr($smsDate010),
  3385.                     "lien" => "{$_ENV['BASE_client']}search",
  3386.                     "heure" => substr($smsDate1115),
  3387.                     "patientName" => $client->getLastName(),
  3388.                     'titre' => 'Votre rendez-vous est annulé :',
  3389.                     'centerName' => $rdv->getIdCentre()->getName(),
  3390.                     'centerPostal' => $rdv->getIdCentre()->getPostale(),
  3391.                     'centerCity' => $rdv->getIdCentre()->getCity(),
  3392.                     'centerAddress' => $rdv->getIdCentre()->getAddress(),
  3393.                     'centerPhone' => $rdv->getIdCentre()->getPhone(),
  3394.                     'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  3395.                     'audioMail' => $rdv->getIdAudio()->getMail(),
  3396.                     'motif' => $rdv->getIdMotif()->getTitre(),
  3397.                 );
  3398.                 $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  3399.                 $publicFunction->sendEmail($params$rdv->getIdAudio()->getMail(), $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject188);
  3400.                 $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.";
  3401.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$rdv->getIdAudio()->getPhone());
  3402.             }
  3403.         }
  3404.         $entityManager->flush();
  3405.         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"]))) {
  3406.             
  3407.             if (is_null($rdv->getIdClientTemp())) {
  3408.                 $clientRDV $this->getDoctrine()
  3409.                     ->getRepository(Client::class)
  3410.                     ->findOneBy(['id' => $rdv->getIdClient()->getId()]);
  3411.                 $clientRDV->setName($data["prenom_patient"]);
  3412.                 $clientRDV->setLastname($data["nom_patient"]);
  3413.                 $clientRDV->setMail($data["mail_patient"]);
  3414.                 $clientRDV->setPhone($data["portable_patient"]);
  3415.                 $clientRDV->setPhoneFixe($data["fixe_patient"]);
  3416.             } else {
  3417.                 $clientRDV $this->getDoctrine()
  3418.                     ->getRepository(ClientTemp::class)
  3419.                     ->findOneBy(['id' => $rdv->getIdClientTemp()->getId()]);
  3420.                 $clientRDV->setName($data["prenom_patient"]);
  3421.                 $clientRDV->setLastname($data["nom_patient"]);
  3422.                 $clientRDV->setMail($data["mail_patient"]);
  3423.                 $clientRDV->setPhone($data["portable_patient"]);
  3424.                 $clientRDV->setPhoneFixe($data["fixe_patient"]);
  3425.             }
  3426.             if (!empty($data["birthday_patient"])) {
  3427.                 $birth \DateTime::createFromFormat("Y-m-d"$data["birthday_patient"]);
  3428.                 $clientRDV->setBirthdate($birth);
  3429.             }
  3430.             
  3431.             $entityManager->flush();
  3432.         }
  3433.         if (is_null($rdv->getIdClient())) {
  3434.             $prenom_patient $rdv->getIdClientTemp()->getName();
  3435.             $nom_patient $rdv->getIdClientTemp()->getLastname();
  3436.             $mail_patient $rdv->getIdClientTemp()->getMail();
  3437.             $portable_patient $rdv->getIdClientTemp()->getPhone();
  3438.             $fixe_patient $rdv->getIdClientTemp()->getPhoneFixe();
  3439.             $birthday $rdv->getIdClientTemp()->getBirthdate();
  3440.         } elseif (is_null($rdv->getIdClientTemp())) {
  3441.             $prenom_patient =  $rdv->getIdClient()->getName();
  3442.             $nom_patient $rdv->getIdClient()->getLastname();
  3443.             $mail_patient $rdv->getIdClient()->getMail();
  3444.             $portable_patient $rdv->getIdClient()->getPhone();
  3445.             $fixe_patient $rdv->getIdClient()->getPhoneFixe();
  3446.             $birthday $rdv->getIdClient()->getBirthdate();
  3447.         } else {
  3448.             $prenom_patient "";
  3449.             $nom_patient "";
  3450.             $mail_patient "";
  3451.             $portable_patient "";
  3452.             $fixe_patient "";
  3453.             $birthday "";
  3454.         }
  3455.         /* generate sms notif on update */
  3456.         // update sms notification     
  3457.         $rdvSms->updateRdvSms($rdv);
  3458.         // google calendar update
  3459.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  3460.             ->findBy(array('audio' => $rdv->getIdAudio()));
  3461.         $data['rdv'] = $rdv->getId();
  3462.         if ($rdv->getIdClient() !== null) {
  3463.             $data["client_id"] = $rdv->getIdClient()->getId();
  3464.         }
  3465.         if ($rdv->getIdClientTemp() !== null) {
  3466.             $data["client_id_temp"] = $rdv->getIdClientTemp()->getId();
  3467.         }
  3468.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  3469.             ->findBy(array('rdv' => $rdv));
  3470.         foreach ($rdvEvents as $rdvEvent) {
  3471.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  3472.             $googleCalendar->updateEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
  3473.         }
  3474.         $synchronisationCosium $this->getDoctrine()->getRepository(SynchronisationCosium::class)->findOneBy(["audio" => $rdv->getIdAudio()->getId()]);
  3475.         $cosiumCenter $this->getDoctrine()->getRepository(CosiumCenter::class)->findOneBy(["synchronisationCosium" => $synchronisationCosium"center" => $rdv->getIdCentre()]);
  3476.         if ($cosiumCenter) {
  3477.             $this->clientCosiumService->deleteRdv($synchronisationCosium$rdv);
  3478.             $this->clientCosiumService->createAgenda($synchronisationCosium$rdv$cosiumCenter);
  3479.         }
  3480.         return new Response(json_encode(([
  3481.             "id" => $rdv->getId(),
  3482.             "motif_id" => $rdv->getIdMotif()->getId(),
  3483.             "motif_libelle" => $rdv->getIdMotif()->getTitre(),
  3484.             "audio_id" => $rdv->getIdAudio()->getId(),
  3485.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  3486.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  3487.             "fullName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  3488.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  3489.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  3490.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  3491.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  3492.             "centre_name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : null,
  3493.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  3494.             "etat_id" => $rdv->getIdEtat()->getId(),
  3495.             "date" => $rdv->getDate(),
  3496.             "comment" => $rdv->getComment(),
  3497.             "note" => $rdv->getNote(),
  3498.             "review" => $rdv->getReview(),
  3499.             "clientEtatId" => $client->getClientStatus() ? $client->getClientStatus()->getId() : 0,
  3500.             "prenom_patient" => $prenom_patient,
  3501.             "nom_patient" => $nom_patient,
  3502.             "mail_patient" => $mail_patient,
  3503.             "portable_patient" => $portable_patient,
  3504.             "fixe_patient" => $fixe_patient,
  3505.             "birthday" => $birthday,
  3506.             "status" => 200,
  3507.         ])));
  3508.     }
  3509.     /**
  3510.      * @Route("/rdv-by-patient/{id}", name="editRdvByIDFromPatient", methods={"PUT"})
  3511.      */
  3512.     public function editRdvByIDFromPatient(PublicFunction $publicFunctionRdv $rdvRequest $request): Response
  3513.     {
  3514.         $pastDate $rdv->getDate();
  3515.         $pastDuration $rdv->getDuration();
  3516.         $data json_decode($request->getContent(), true);
  3517.         $entityManager $this->getDoctrine()->getManager();
  3518.         if (!isset($data["token"])) {
  3519.             return new Response(json_encode([
  3520.                 "message" => "Pas de token n'a été spécifié",
  3521.                 "status" => 401,
  3522.             ]), 401);
  3523.         }
  3524.         /** @var Token */
  3525.         $token $this->getDoctrine()
  3526.             ->getRepository(Token::class)
  3527.             ->findOneBy(['token' => $data["token"]]);
  3528.         if (!$token) {
  3529.             return new Response(json_encode([
  3530.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  3531.                 "status" => 404,
  3532.             ]), 404);
  3533.         }
  3534.         // get token age
  3535.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  3536.         // if the token if older than 7 days
  3537.         if ($dateDiff->7) {
  3538.             $entityManager->remove($token);
  3539.             $entityManager->flush();
  3540.             return $this->json([
  3541.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  3542.                 'path' => 'src/Controller/ClientController.php',
  3543.                 "status" => 401,
  3544.             ], 401);
  3545.         }
  3546.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  3547.             return new Response(json_encode([
  3548.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  3549.                 "status" => 404,
  3550.             ]), 404);
  3551.         }
  3552.         if (isset($data["etat_id"])) {
  3553.             $etat $this->getDoctrine()
  3554.                 ->getRepository(EtatRdv::class)
  3555.                 ->findOneBy(['id' => $data["etat_id"]]);
  3556.             if ($etat == null) {
  3557.                 return new Response(json_encode(([
  3558.                     'message' => 'Error, no etat found at this id',
  3559.                     'path' => 'src/Controller/TrustedUserController.php',
  3560.                     "status" => 400,
  3561.                 ])), 400);
  3562.             }
  3563.             $rdv->setIdEtat($etat);
  3564.         }
  3565.         if (isset($data["audio_id"])) {
  3566.             $audio $this->getDoctrine()
  3567.                 ->getRepository(Audio::class)
  3568.                 ->findOneBy(['id' => $data["audio_id"]]);
  3569.             if ($audio == null) {
  3570.                 return new Response(json_encode(([
  3571.                     'message' => 'Error, no audio found at this id',
  3572.                     'path' => 'src/Controller/TrustedUserController.php',
  3573.                     "status" => 400,
  3574.                 ])), 400);
  3575.             }
  3576.             $rdv->setIdAudio($audio);
  3577.         }
  3578.         if (isset($data["motif_id"])) {
  3579.             $motif $this->getDoctrine()
  3580.                 ->getRepository(Motif::class)
  3581.                 ->find($data["motif_id"]);
  3582.             if ($motif == null) {
  3583.                 return new Response(json_encode(([
  3584.                     'message' => 'Error, no motif found at this id',
  3585.                     'path' => 'src/Controller/TrustedUserController.php',
  3586.                     "status" => 400,
  3587.                 ])), 400);
  3588.             }
  3589.             $rdv->setIdMotif($motif);
  3590.         }
  3591.         if (isset($data["client_id"])) {
  3592.             $client $this->getDoctrine()
  3593.                 ->getRepository(Client::class)
  3594.                 ->findOneBy(['id' => $data["client_id"]]);
  3595.             if ($client == null) {
  3596.                 return new Response(json_encode(([
  3597.                     'message' => 'Error, no client found at this id',
  3598.                     'path' => 'src/Controller/TrustedUserController.php',
  3599.                     "status" => 400,
  3600.                 ])), 400);
  3601.             }
  3602.             $rdv->setIdClient($client);
  3603.         }
  3604.         if (isset($data["date"])) {
  3605.             // remove the taken schedule by rdv to make sure there is no overlap
  3606.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  3607.             $dateInput \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  3608.             $audioMotif $this->getDoctrine()
  3609.                 ->getRepository(AudioMotif::class)
  3610.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  3611.             if ($audioMotif == null) {
  3612.                 return new Response(json_encode(([
  3613.                     'message' => 'Error, no motif of this id found at this audio',
  3614.                     'path' => 'src/Controller/RdvController.php',
  3615.                     "status" => 400,
  3616.                 ])), 400);
  3617.             }
  3618.             if ($rdv->getIdAudio()->getIsIndie()) {
  3619.                 if ($rdv->getIdCentre()) {
  3620.                     // regular centre audio indie
  3621.                     /** @var AudioCentre */
  3622.                     $liaison $this->getDoctrine()
  3623.                         ->getRepository(AudioCentre::class)
  3624.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  3625.                     if ($liaison == null) {
  3626.                         return new Response(json_encode(([
  3627.                             'message' => 'Error, audio isnt part of the centre',
  3628.                             'path' => 'src/Controller/RdvController.php',
  3629.                             "status" => 400,
  3630.                         ])), 400);
  3631.                     }
  3632.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  3633.                         return new Response(json_encode(([
  3634.                             'message' => 'Error, no horaire found for this audio',
  3635.                             'path' => 'src/Controller/RdvController.php',
  3636.                             "status" => 400,
  3637.                         ])), 400);
  3638.                     }
  3639.                 } else {
  3640.                     // lieu audio indie
  3641.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  3642.                         return new Response(json_encode(([
  3643.                             'message' => 'Error, no horaire found for this audio',
  3644.                             'path' => 'src/Controller/RdvController.php',
  3645.                             "status" => 400,
  3646.                         ])), 400);
  3647.                     }
  3648.                 }
  3649.             } else {
  3650.                 // regular centre
  3651.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  3652.                     return new Response(json_encode(([
  3653.                         'message' => 'Error, no horaire found for this audio',
  3654.                         'path' => 'src/Controller/RdvController.php',
  3655.                         "status" => 400,
  3656.                     ])), 400);
  3657.                 }
  3658.             }
  3659.             $rdv->setDate($date);
  3660.         }
  3661.         if (isset($data["comment"]) && $token->getIdClient()) {
  3662.             $rdv->setComment($data["comment"]);
  3663.         }
  3664.         if (isset($data["review"]) && $token->getIdClient()) {
  3665.             $rdv->setReview($data["review"]);
  3666.         }
  3667.         if (isset($data["note"])) {
  3668.             $rdv->setNote($data["note"]);
  3669.         }
  3670.         if (isset($data["duree"])) {
  3671.             $rdv->setDuration($data["duree"]);
  3672.         }
  3673.         ////// SMSEMAIL A décommenter pour activer l'envoi de SMS + MAIL pour modification annulation de RDV, coté audio / client SMSEMAIL ////
  3674.         $date $rdv->getDate();
  3675.         $smsDate $date->format('d-m-Y H:i');
  3676.         $oldDate $pastDate->format('d-m-Y H:i');
  3677.         $locale 'fr_FR';
  3678.         $formatter = new IntlDateFormatter(
  3679.             $locale,
  3680.             IntlDateFormatter::FULL,
  3681.             IntlDateFormatter::SHORT,
  3682.             null,
  3683.             IntlDateFormatter::GREGORIAN,
  3684.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  3685.         );
  3686.         $smsDateLongFormat $formatter->format($date);
  3687.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  3688.         $frenchDate ucfirst($frenchDate);
  3689.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  3690.         // notif client
  3691.         if ($rdv->getIdEtat()->getId() != 2) {
  3692.             if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  3693.                 $params = array(
  3694.                     "lienModifier" => "{$_ENV['BASE_client']}mes-rendez-vous",
  3695.                     "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  3696.                     "date" => $smsDateLongFormat,
  3697.                     "heure" => substr($smsDate1115),
  3698.                     "motif" => $rdv->getIdMotif()->getTitre(),
  3699.                     "centerName" => $rdv->getIdCentre()->getName(),
  3700.                     "centerAddress" => $rdv->getIdCentre()->getAddress(),
  3701.                     "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  3702.                     "audioMail" => $rdv->getIdAudio()->getMail(),
  3703.                     "centerPhone" => $rdv->getIdCentre()->getPhone(),
  3704.                     "centerCity" => $rdv->getIdCentre()->getCity(),
  3705.                     "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  3706.                     'titre' => 'Votre rendez-vous est modifié pour le',
  3707.                     'frenchDate' => $frenchDate,
  3708.                 );
  3709.                 $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  3710.                 $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject184);
  3711.                 $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.";
  3712.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  3713.             }
  3714.         }
  3715.         //     //// == suppression
  3716.         else if ($rdv->getIdEtat()->getId() == 2) {
  3717.             //if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  3718.             //if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {                   
  3719.             $params = array(
  3720.                 "date" => substr($smsDate010),
  3721.                 "lien" => "{$_ENV['BASE_client']}audioprothesiste/{$rdv->getIdCentre()->getCity()}/{$rdv->getIdCentre()->getPostale()}/{$rdv->getIdCentre()->getName()}/prise-de-rdv-audioprothesiste-rapide/{$rdv->getIdCentre()->getId()}",
  3722.                 "heure" => substr($smsDate1115),
  3723.                 "patientName" => $client->getLastName(),
  3724.                 'titre' => 'Votre rendez-vous est annulé :',
  3725.                 'centerName' => $rdv->getIdCentre()->getName(),
  3726.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  3727.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  3728.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  3729.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  3730.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  3731.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  3732.                 'motif' => $rdv->getIdMotif()->getTitre(),
  3733.             );
  3734.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  3735.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject203);
  3736.             $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  3737.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  3738.             //}
  3739.         }
  3740.         // set center
  3741.         if (isset($data["centre_id"])) {
  3742.             $entityManager $this->getDoctrine()->getManager();
  3743.             $centreId $data["centre_id"];
  3744.             $centre $entityManager->getRepository(Centre::class)->find($centreId);
  3745.             if (!$centre) {
  3746.                 return $this->json([
  3747.                     'message' => 'Error, no Centre found with this ID',
  3748.                     'path' => 'src/Controller/YourController.php',
  3749.                 ]);
  3750.             }
  3751.             $rdv->setIdCentre($centre);
  3752.         }
  3753.         $rdv->setGoogleAgendaImported(false);
  3754.         //notif Audio
  3755.         if ($rdv->getIdEtat()->getId() != 2) {
  3756.             if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  3757.                 $params = array(
  3758.                     "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  3759.                     "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  3760.                     "date" => $pastDate->format("y-m-d"),
  3761.                     "heure" => $pastDate->format("H:i"),
  3762.                     'clientPhone' => $client->getPhone(),
  3763.                     'clientCivilite' => $client->getCivilite(),
  3764.                     'clientNom' => $client->getLastname(),
  3765.                     'clientPrenom' => $client->getName(),
  3766.                     'clientPostal' => $client->getPostal(),
  3767.                     'clientMail' => $client->getMail(),
  3768.                     "birthdate" => $rdv->getIdClient()->getBirthdate()->format("y-m-d"),
  3769.                     "mail" => $rdv->getIdClient()->getMail(),
  3770.                     "phone" => $rdv->getIdClient()->getPhone(),
  3771.                     "motif" => $rdv->getIdMotif()->getTitre(),
  3772.                     "address" => $rdv->getIdCentre()->getAddress(),
  3773.                     "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getLastName() . ' ' $rdv->getIdAudio()->getName(),
  3774.                     "newRdvDate" => substr($smsDate010),
  3775.                     "newRdvHour" => substr($smsDate1115),
  3776.                     "centerName" => $rdv->getIdCentre()->getName(),
  3777.                     "centerAddress" => $rdv->getIdCentre()->getAddress(),
  3778.                     "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  3779.                     'titre' => "Modification de Rendez-vous My Audio de {$rdv->getIdClient()->getLastname()}",
  3780.                     "urlPro" => "{$_ENV['BASE_logiciel']}",
  3781.                     "idPatient" => $rdv->getIdClient()->getId(),
  3782.                 );
  3783.                 $subject "🔀 Rendez-vous My Audio modifié par " $client->getCivilite() . " " $client->getName() . " " $client->getLastname();
  3784.                 $publicFunction->sendEmail($params$rdv->getIdAudio()->getMail(), $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject185);
  3785.                 $subjectMyAudio "🔀 Le patient " $client->getCivilite() . " " $client->getName() . " " $client->getLastname() . "  a modifié son rendez-vous My Audio";
  3786.                 $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subjectMyAudio204);
  3787.                 $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.";
  3788.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$rdv->getIdAudio()->getPhone());
  3789.             }
  3790.         } else if ($rdv->getIdEtat()->getId() == 2) {
  3791.             $params = array(
  3792.                 "date" => substr($smsDate010),
  3793.                 "heure" => substr($smsDate1115),
  3794.                 "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  3795.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  3796.                 "motif" => $rdv->getIdMotif()->getTitre(),
  3797.                 "centerAddress" => $rdv->getIdCentre()->getAddress(),
  3798.                 "centerPostal" => $rdv->getIdCentre()->getPostale(),
  3799.                 "centerCity" => $rdv->getIdCentre()->getCity(),
  3800.                 "centerName" => $rdv->getIdCentre()->getName(),
  3801.                 "clientNom" => $rdv->getIdClient()->getLastname(),
  3802.                 "clientPrenom" => $rdv->getIdClient()->getName(),
  3803.                 "clientMail" => $rdv->getIdClient()->getMail(),
  3804.                 "clientPhone" => $rdv->getIdClient()->getPhone(),
  3805.                 'titre' => "Annulation du Rendez-vous avec le patient {$rdv->getIdClient()->getLastname()}",
  3806.                 "proUrl" => "{$_ENV['BASE_logiciel']}",
  3807.                 "idPatient" => $rdv->getIdClient()->getId(),
  3808.             );
  3809.             $subject "❌ Annulation du rendez-vous par le patient " $client->getCivilite() . " " $client->getName() . " " $client->getLastname();
  3810.             $publicFunction->sendEmail($params$rdv->getIdAudio()->getMail(), $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject187);
  3811.             $subject "❌ Annulation du rendez-vous par le patient " $client->getCivilite() . " " $client->getName() . " " $client->getLastname();
  3812.             $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject195);
  3813.             $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.";
  3814.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$rdv->getIdAudio()->getPhone());
  3815.         }
  3816.         $entityManager->flush();
  3817.         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"]))) {
  3818.             $birth \DateTime::createFromFormat("Y-m-d"$data["birthday_patient"]);
  3819.             if (is_null($rdv->getIdClientTemp())) {
  3820.                 $clientRDV $this->getDoctrine()
  3821.                     ->getRepository(Client::class)
  3822.                     ->findOneBy(['id' => $rdv->getIdClient()->getId()]);
  3823.                 $clientRDV->setName($data["prenom_patient"]);
  3824.                 $clientRDV->setLastname($data["nom_patient"]);
  3825.                 $clientRDV->setBirthdate($birth);
  3826.                 $clientRDV->setMail($data["mail_patient"]);
  3827.                 $clientRDV->setPhone($data["portable_patient"]);
  3828.                 $clientRDV->setPhoneFixe($data["fixe_patient"]);
  3829.             } else {
  3830.                 $clientRDV $this->getDoctrine()
  3831.                     ->getRepository(ClientTemp::class)
  3832.                     ->findOneBy(['id' => $rdv->getIdClientTemp()->getId()]);
  3833.                 $clientRDV->setName($data["prenom_patient"]);
  3834.                 $clientRDV->setLastname($data["nom_patient"]);
  3835.                 $clientRDV->setBirthdate($birth);
  3836.                 $clientRDV->setMail($data["mail_patient"]);
  3837.                 $clientRDV->setPhone($data["portable_patient"]);
  3838.                 $clientRDV->setPhoneFixe($data["fixe_patient"]);
  3839.             }
  3840.             $entityManager->flush();
  3841.         }
  3842.         if (is_null($rdv->getIdClient())) {
  3843.             $prenom_patient $rdv->getIdClientTemp()->getName();
  3844.             $nom_patient $rdv->getIdClientTemp()->getLastname();
  3845.             $mail_patient $rdv->getIdClientTemp()->getMail();
  3846.             $portable_patient $rdv->getIdClientTemp()->getPhone();
  3847.             $fixe_patient $rdv->getIdClientTemp()->getPhoneFixe();
  3848.             $birthday $rdv->getIdClientTemp()->getBirthdate();
  3849.         } elseif (is_null($rdv->getIdClientTemp())) {
  3850.             $prenom_patient =  $rdv->getIdClient()->getName();
  3851.             $nom_patient $rdv->getIdClient()->getLastname();
  3852.             $mail_patient $rdv->getIdClient()->getMail();
  3853.             $portable_patient $rdv->getIdClient()->getPhone();
  3854.             $fixe_patient $rdv->getIdClient()->getPhoneFixe();
  3855.             $birthday $rdv->getIdClient()->getBirthdate();
  3856.         } else {
  3857.             $prenom_patient "";
  3858.             $nom_patient "";
  3859.             $mail_patient "";
  3860.             $portable_patient "";
  3861.             $fixe_patient "";
  3862.             $birthday "";
  3863.         }
  3864.         return new Response(json_encode(([
  3865.             "id" => $rdv->getId(),
  3866.             "motif_id" => $rdv->getIdMotif()->getId(),
  3867.             "motif_libelle" => $rdv->getIdMotif()->getTitre(),
  3868.             "audio_id" => $rdv->getIdAudio()->getId(),
  3869.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  3870.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  3871.             "fullName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  3872.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  3873.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  3874.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  3875.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  3876.             "centre_name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : null,
  3877.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  3878.             "etat_id" => $rdv->getIdEtat()->getId(),
  3879.             "date" => $rdv->getDate(),
  3880.             "comment" => $rdv->getComment(),
  3881.             "note" => $rdv->getNote(),
  3882.             "review" => $rdv->getReview(),
  3883.             "prenom_patient" => $prenom_patient,
  3884.             "nom_patient" => $nom_patient,
  3885.             "mail_patient" => $mail_patient,
  3886.             "portable_patient" => $portable_patient,
  3887.             "fixe_patient" => $fixe_patient,
  3888.             "birthday" => $birthday,
  3889.             "status" => 200,
  3890.         ])));
  3891.     }
  3892.     /**
  3893.      * @Route("/rdv/{id}/supp", name="suppRdvByID", methods={"PUT"})
  3894.      */
  3895.     public function suppRdvByID(PublicFunction $publicFunctionRdv $rdvRequest $requestGoogleCalendarService $googleCalendarRdvSmsService $rdvSms): Response
  3896.     {
  3897.         $pastDate $rdv->getDate();
  3898.         $data json_decode($request->getContent(), true);
  3899.         $entityManager $this->getDoctrine()->getManager();
  3900.         if (!isset($data["token"])) {
  3901.             return new Response(json_encode([
  3902.                 "message" => "Pas de token n'a été spécifié",
  3903.                 "status" => 401,
  3904.             ]), 401);
  3905.         }
  3906.         /** @var Token */
  3907.         $token $this->getDoctrine()
  3908.             ->getRepository(Token::class)
  3909.             ->findOneBy(['token' => $data["token"]]);
  3910.         if (!$token) {
  3911.             return new Response(json_encode([
  3912.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  3913.                 "status" => 404,
  3914.             ]), 404);
  3915.         }
  3916.         // get token age
  3917.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  3918.         // if the token if older than 7 days
  3919.         if ($dateDiff->7) {
  3920.             $entityManager->remove($token);
  3921.             $entityManager->flush();
  3922.             return $this->json([
  3923.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  3924.                 'path' => 'src/Controller/ClientController.php',
  3925.                 "status" => 401,
  3926.             ], 401);
  3927.         }
  3928.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  3929.             return new Response(json_encode([
  3930.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  3931.                 "status" => 404,
  3932.             ]), 404);
  3933.         }
  3934.         // delete google agenda event
  3935.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  3936.             ->findBy(array('rdv' => $rdv));
  3937.         //dd($rdvEvents);
  3938.         $synchronisationCosium $this->getDoctrine()->getRepository(SynchronisationCosium::class)->findOneBy(["audio" => $rdv->getIdAudio()->getId()]);
  3939.         $cosiumCenter $this->getDoctrine()->getRepository(CosiumCenter::class)->findBy(["synchronisationCosium" => $synchronisationCosium"center" => $rdv->getIdCentre()]);
  3940.         if ($cosiumCenter) {
  3941.             $this->clientCosiumService->deleteRdv($synchronisationCosium$rdv);
  3942.         }
  3943.         foreach ($rdvEvents as $rdvEvent) {
  3944.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  3945.             $googleCalendar->deleteEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId());
  3946.             $entityManager->remove($rdvEvent);
  3947.             $entityManager->flush();
  3948.         }
  3949.         $etat $this->getDoctrine()
  3950.             ->getRepository(EtatRdv::class)
  3951.             ->findOneBy(['id' => 2]);
  3952.         if ($etat == null) {
  3953.             return new Response(json_encode(([
  3954.                 'message' => 'Error, no etat found at this id',
  3955.                 'path' => 'src/Controller/TrustedUserController.php',
  3956.                 "status" => 400,
  3957.             ])), 400);
  3958.         }
  3959.         $rdv->setIdEtat($etat);
  3960.         $rdv->setCacher(1);
  3961.         ////// SMSEMAIL A décommenter pour activer l'envoi de SMS + MAIL pour modification annulation de RDV, coté audio / client SMSEMAIL ////
  3962.         $date $rdv->getDate();
  3963.         $smsDate $date->format('d-m-Y H:i');
  3964.         $oldDate $pastDate->format('d-m-Y H:i');
  3965.         $locale 'fr_FR';
  3966.         $formatter = new IntlDateFormatter(
  3967.             $locale,
  3968.             IntlDateFormatter::FULL,
  3969.             IntlDateFormatter::SHORT,
  3970.             null,
  3971.             IntlDateFormatter::GREGORIAN,
  3972.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  3973.         );
  3974.         $smsDateLongFormat $formatter->format($date);
  3975.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  3976.         $frenchDate ucfirst($frenchDate);
  3977.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  3978.         // notif client
  3979.         if ($rdv->getIdEtat()->getId() != 2) {
  3980.             $params = array(
  3981.                 "lienModifier" => "{$_ENV['BASE_client']}mes-rendez-vous",
  3982.                 "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  3983.                 "date" => $smsDateLongFormat,
  3984.                 "heure" => substr($smsDate1115),
  3985.                 "motif" => $rdv->getIdMotif()->getTitre(),
  3986.                 "centerName" => $rdv->getIdCentre()->getName(),
  3987.                 "centerAddress" => $rdv->getIdCentre()->getAddress(),
  3988.                 "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  3989.                 "audioMail" => $rdv->getIdAudio()->getMail(),
  3990.                 "centerPhone" => $rdv->getIdCentre()->getPhone(),
  3991.                 "centerCity" => $rdv->getIdCentre()->getCity(),
  3992.                 "clientEmail" => $client->getMail(),
  3993.                 "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  3994.                 'titre' => 'Votre rendez-vous est modifié pour le',
  3995.                 'frenchDate' => $frenchDate
  3996.             );
  3997.             $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  3998.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject205);
  3999.             $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.";
  4000.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  4001.             // creer un mail de notif pour myAudio + créé le template LP | MA | RR - Modification du RDV - Centre Auditif - MyAudio
  4002.             $subjectMyaudio "Rendez-vous My Audio a été modifié par l'audioprothésiste " $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName();
  4003.             $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$client->getName() . ' ' $client->getLastName(), $subjectMyaudio206);
  4004.         }
  4005.         //     //// == suppression
  4006.         else if ($rdv->getIdEtat()->getId() == 2) {
  4007.             $params = array(
  4008.                 "date" => substr($smsDate010),
  4009.                 "lien" => "{$_ENV['BASE_client']}search",
  4010.                 "heure" => substr($smsDate1115),
  4011.                 "patientName" => $client->getLastName() . ' ' $client->getName(),
  4012.                 'titre' => 'Votre rendez-vous est annulé :',
  4013.                 'centerName' => $rdv->getIdCentre()->getName(),
  4014.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4015.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  4016.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4017.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  4018.                 "clientEmail" => $client->getMail() ?? '',
  4019.                 "clientPhone" => $client->getPhone() ?? '',
  4020.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  4021.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  4022.                 'motif' => $rdv->getIdMotif()->getTitre(),
  4023.             );
  4024.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  4025.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject188);
  4026.             $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  4027.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  4028.             // creer un mail de notif pour myAudio + créé le template LP | MA | RR - Annlation du RDV - Centre Auditif - MyAudio
  4029.             $subjectMyaudio $rdv->getIdCentre()->getName() . " a annulé un rendez-vous My Audio avec " $client->getName() . ' ' $client->getLastName();
  4030.             $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$client->getName() . ' ' $client->getLastName(), $subjectMyaudio207);
  4031.         }
  4032.         //notif Audio
  4033.         if ($rdv->getIdEtat()->getId() != 2) {
  4034.             $params = array(
  4035.                 "lienModifier" => "{$_ENV['BASE_logiciel']}rdv",
  4036.                 "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  4037.                 "date" => substr($smsDate010),
  4038.                 "frenchDate" => $frenchDate,
  4039.                 "heure" => substr($smsDate1115),
  4040.                 'motif' => $rdv->getIdMotif()->getTitre(),
  4041.                 'clientPhone' => $client->getPhone(),
  4042.                 'clientNom' => $client->getLastname(),
  4043.                 'clientPrenom' => $client->getName(),
  4044.                 'clientCivilite' => $client->getCivilite(),
  4045.                 'clientPostal' => $client->getPostal(),
  4046.                 'clientMail' => $client->getMail(),
  4047.                 'centerName' => $rdv->getIdCentre()->getName(),
  4048.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4049.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  4050.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4051.                 'idPatient' => $client->getId(),
  4052.                 'proUrl' => "{$_ENV['BASE_logiciel']}",
  4053.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  4054.                 'titre' => 'Votre rendez-vous est modifié pour le :'
  4055.             );
  4056.             $subject "🔀 Rendez-vous My Audio modifié du " $frenchDate " à " substr($smsDate1115);
  4057.             $publicFunction->sendEmail($params$rdv->getIdAudio()->getMail(), $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject186);
  4058.             $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.";
  4059.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$rdv->getIdAudio()->getPhone());
  4060.         } else if ($rdv->getIdEtat()->getId() == 2) {
  4061.             /* $params = array(  
  4062.                     "date" => substr($smsDate, 0, 10),
  4063.                     "lien"=> "{$_ENV['BASE_client']}search",
  4064.                     "heure" =>substr($smsDate, 11, 15),
  4065.                     "patientName" => $client->getLastName(),
  4066.                     'titre' => 'Votre rendez-vous est annulé :',
  4067.                     'centerName' => $rdv->getIdCentre()->getName(),
  4068.                     'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4069.                     'centerCity' => $rdv->getIdCentre()->getCity(),
  4070.                     'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4071.                     'centerPhone' => $rdv->getIdCentre()->getPhone(),
  4072.                     'audioproName' => $rdv->getIdAudio()->getCivilite().' '. $rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(),                    
  4073.                     'audioMail' => $rdv->getIdAudio()->getMail(),
  4074.                     'motif' => $rdv->getIdMotif()->getTitre(),
  4075.                 );
  4076.                 $subject = "Rendez-vous My Audio annulé avec " . $rdv->getIdCentre()->getName();
  4077.                 $publicFunction->sendEmail($params, $rdv->getIdAudio()->getMail(), $rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(), $subject, 188 );
  4078.                 $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.";
  4079.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $rdv->getIdAudio()->getPhone());
  4080.                 */
  4081.         }
  4082.         // delete sms notification     
  4083.         $rdvSms->deleteAssociatedRdvSms($rdv);
  4084.         // delete client device
  4085.         /*$clientDevice = $this->getDoctrine()->getRepository(ClientDevice::class)->findOneBy(['rdv' => $rdv]);
  4086. if($clientDevice)
  4087. {
  4088. if ($client instanceof Client) {
  4089.     $nextRdvs = $this->getDoctrine()
  4090.         ->getRepository(Rdv::class)
  4091.         ->findBy([
  4092.             "id_client" => $rdv->getIdClient(),
  4093.             "id_motif" => ['106', '107', '108', '109'] 
  4094.         ]);
  4095.         $client->setClientStatus(null);
  4096. } elseif ($client instanceof ClientTemp) {
  4097.  $nextRdvs = $this->getDoctrine()
  4098.         ->getRepository(Rdv::class)
  4099.         ->findBy([
  4100.             "id_client_temp" => $rdv->getIdClientTemp(),
  4101.             "id_motif" => ['106', '107', '108', '109'] 
  4102.         ]);
  4103.         $client->setClientStatus(null);
  4104.     } 
  4105.     $locale = 'fr_FR';
  4106.     $fmt = new IntlDateFormatter($locale, IntlDateFormatter::FULL, IntlDateFormatter::NONE);
  4107.     $fmt->setPattern("EEEE dd MMMM yyyy"); 
  4108.     if($nextRdvs){
  4109.     $params = array(  
  4110.                 "title" => "Affectation de votre appareil et programmation de vos rendez-vous",
  4111.                 "centerName" => "{$rdv->getIdCentre()->getName()}",
  4112.                 "audioName" => "{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastName()}",
  4113.                 "centerAddress" => "{$rdv->getIdCentre()->getAddress()}",
  4114.                 "device" => "{$clientDevice->getDevice()->getModel()}",
  4115.                 "ears" => "{$clientDevice->getSettingDevice()->getName()}",
  4116.                 "rdvOneDate" => "{$fmt->format($nextRdvs['0']->getDate())}",
  4117.                 "rdvOneHour" => "{$nextRdvs['0']->getDate()->format('H:i')}",
  4118.                 "rdvTwoDate" => "{$fmt->format($nextRdvs['1']->getDate())}",
  4119.                 "rdvTwoHour" => "{$nextRdvs['1']->getDate()->format('H:i')}",
  4120.                 "rdvThreeDate" => "{$fmt->format($nextRdvs['2']->getDate())}",
  4121.                 "rdvThreeHour" => "{$nextRdvs['2']->getDate()->format('H:i')}",
  4122.                 "rdvFourDate" => "{$fmt->format($nextRdvs['3']->getDate())}",
  4123.                 "rdvFourHour" => "{$nextRdvs['3']->getDate()->format('H:i')}",
  4124.             );
  4125.     
  4126.             $publicFunction->sendEmail($params, $client->getMail(), $client->getName().' '.$client->getLastName(), "Annulation de vos prochains RDV", 162 );
  4127.         }
  4128.     foreach($nextRdvs as $rdv)
  4129.     {
  4130.         $entityManager->remove($rdv);
  4131.     }
  4132.     $entityManager->persist($client);
  4133.     $entityManager->remove($clientDevice);
  4134.     $entityManager->flush();
  4135. }*/
  4136.         $entityManager->flush();
  4137.         return new Response(json_encode(([
  4138.             "id" => $rdv->getId(),
  4139.             "motif_id" => $rdv->getIdMotif()->getId(),
  4140.             "motif_libelle" => $rdv->getIdMotif()->getTitre(),
  4141.             "audio_id" => $rdv->getIdAudio()->getId(),
  4142.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  4143.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  4144.             "fullName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  4145.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  4146.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  4147.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  4148.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  4149.             "centre_name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : null,
  4150.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  4151.             "etat_id" => $rdv->getIdEtat()->getId(),
  4152.             "date" => $rdv->getDate(),
  4153.             "comment" => $rdv->getComment(),
  4154.             "note" => $rdv->getNote(),
  4155.             "review" => $rdv->getReview(),
  4156.             "status" => 200,
  4157.         ])));
  4158.     }
  4159.     /**
  4160.      * @Route("/rdv/calendar", name="postRdvCalendar", methods={"POST"})
  4161.      */
  4162.     public function postRdvCalendar(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendarRdvSmsService $rdvSms): Response
  4163.     {
  4164.         $data json_decode($request->getContent(), true);
  4165.         if (!isset($data["token"])) {
  4166.             return new Response(json_encode([
  4167.                 "message" => "Pas de token n'a été spécifié",
  4168.                 "status" => 401,
  4169.             ]), 401);
  4170.         }
  4171.         $entityManager $this->getDoctrine()->getManager();
  4172.         /** @var Token */
  4173.         $token $this->getDoctrine()
  4174.             ->getRepository(Token::class)
  4175.             ->findOneBy(['token' => $data["token"]]);
  4176.         if (!$token) {
  4177.             return new Response(json_encode([
  4178.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  4179.                 "status" => 404,
  4180.             ]), 404);
  4181.         }
  4182.         // get token age
  4183.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  4184.         // if the token if older than 7 days
  4185.         if ($dateDiff->7) {
  4186.             $entityManager->remove($token);
  4187.             $entityManager->flush();
  4188.             return $this->json([
  4189.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  4190.                 'path' => 'src/Controller/ClientController.php',
  4191.                 "status" => 401,
  4192.             ], 401);
  4193.         }
  4194.         // makes the rdv
  4195.         $rdv = new Rdv();
  4196.         if ($token->getIdAudio()) {
  4197.             //if the token if for an audio
  4198.             $audio $token->getIdAudio();
  4199.             if ((isset($data["client_id"]))) {
  4200.                 $client $this->getDoctrine()
  4201.                     ->getRepository(Client::class)
  4202.                     ->findOneBy(['id' => $data["client_id"]]);
  4203.             } else {
  4204.                 $client $this->getDoctrine()
  4205.                     ->getRepository(ClientTemp::class)
  4206.                     ->findOneBy(['id' => $data["client_id_temp"]]);
  4207.             }
  4208.             if ($client == null) {
  4209.                 return new Response(json_encode(([
  4210.                     'message' => 'Error, no client found at this id',
  4211.                     'path' => 'src/Controller/RdvController.php',
  4212.                     "status" => 400,
  4213.                 ])), 400);
  4214.             }
  4215.         } elseif ($token->getIdClient()) {
  4216.             //if the token if for a client
  4217.             $client $token->getIdClient();
  4218.             /** @var Audio */
  4219.             $audio $this->getDoctrine()
  4220.                 ->getRepository(Audio::class)
  4221.                 ->findOneBy(['id' => $data["audio_id"]]);
  4222.             if (isset($data["proche_id"])) {
  4223.                 $proche $this->getDoctrine()
  4224.                     ->getRepository(Proches::class)
  4225.                     ->findOneBy(['id' => $data["proche_id"], "id_client" => $client]);
  4226.             }
  4227.             if ($audio == null) {
  4228.                 return new Response(json_encode(([
  4229.                     'message' => 'Error, no audio found at this id',
  4230.                     'path' => 'src/Controller/RdvController.php',
  4231.                     "status" => 400,
  4232.                 ])), 400);
  4233.             }
  4234.         } else {
  4235.             return new Response(json_encode(([
  4236.                 'message' => 'Error, token is not an audio token',
  4237.                 'path' => 'src/Controller/RdvController.php',
  4238.                 "status" => 400,
  4239.             ])), 400);
  4240.         }
  4241.         $rdv->setIdAudio($audio);
  4242.         if (isset($proche)) {
  4243.             $rdv->setIdProche($proche);
  4244.         }
  4245.         if (isset($data["client_id_temp"])) {
  4246.             $rdv->setIdClientTemp($client);
  4247.         } else {
  4248.             $rdv->setIdClient($client);
  4249.         }
  4250.         $rdv->setCacher(0);
  4251.         /** @var Centre */
  4252.         if (isset($data["centre_id"])) {
  4253.             $centre $this->getDoctrine()
  4254.                 ->getRepository(Centre::class)
  4255.                 ->findOneBy(['id' => $data["centre_id"]]);
  4256.             if ($centre == null) {
  4257.                 return new Response(json_encode(([
  4258.                     'message' => 'Error, no centre found at this id',
  4259.                     'path' => 'src/Controller/RdvController.php',
  4260.                     "status" => 400,
  4261.                 ])), 400);
  4262.             }
  4263.             /** @var AudioCentre */
  4264.             $liaison $this->getDoctrine()
  4265.                 ->getRepository(AudioCentre::class)
  4266.                 ->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
  4267.             if ($liaison == null) {
  4268.                 return new Response(json_encode(([
  4269.                     'message' => 'Error, audio isnt part of the centre',
  4270.                     'path' => 'src/Controller/RdvController.php',
  4271.                     "status" => 400,
  4272.                 ])), 400);
  4273.             }
  4274.             $rdv->setIdCentre($centre);
  4275.         } elseif (isset($data["lieu_id"]) && $audio->getIsIndie()) {
  4276.             // tries to set the lieu if it's an audio indie
  4277.             $lieu $this->getDoctrine()
  4278.                 ->getRepository(Lieu::class)
  4279.                 ->findOneBy(['id' => $data["lieu_id"], 'id_gerant' => $data["audio_id"]]);
  4280.             if ($lieu == null) {
  4281.                 return new Response(json_encode(([
  4282.                     'message' => 'Error, no lieu found at this id',
  4283.                     'path' => 'src/Controller/RdvController.php',
  4284.                     "status" => 400,
  4285.                 ])), 400);
  4286.             }
  4287.             $rdv->setIdLieu($lieu);
  4288.         } else {
  4289.             return new Response(json_encode(([
  4290.                 'message' => 'Error, no lieu/centre id',
  4291.                 'path' => 'src/Controller/RdvController.php',
  4292.                 "status" => 400,
  4293.             ])), 400);
  4294.         }
  4295.         /** @var Motif */
  4296.         $motif $this->getDoctrine()
  4297.             ->getRepository(Motif::class)
  4298.             ->find($data["motif_id"]);
  4299.         if ($motif == null) {
  4300.             return new Response(json_encode(([
  4301.                 'message' => 'Error, no motif found at this id',
  4302.                 'path' => 'src/Controller/RdvController.php',
  4303.                 "status" => 400,
  4304.             ])), 400);
  4305.         }
  4306.         /** @var AudioMotif */
  4307.         $audioMotif $this->getDoctrine()
  4308.             ->getRepository(AudioMotif::class)
  4309.             ->findOneBy(["id_audio" => $audio->getId(), "id_motif" => $data["motif_id"]]);
  4310.         if ($audioMotif == null) {
  4311.             return new Response(json_encode(([
  4312.                 'message' => 'Error, no motif of this id found at this audio',
  4313.                 'path' => 'src/Controller/RdvController.php',
  4314.                 "status" => 400,
  4315.             ])), 400);
  4316.         }
  4317.         // remove the taken schedule by rdv to make sure there is no overlap
  4318.         $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4319.         if (isset($data["note"])) {
  4320.             $rdv->setNote($data["note"]);
  4321.         }
  4322.         // test if the audio is available
  4323.         /*   if (isset($data["lieu_id"]) && $audio->getIsIndie()){
  4324.             if ($publicFunction->calculScheduleFitDate($audio, $date, $audioMotif->getDuration(), null, $lieu) == false) {
  4325.                 return new Response(json_encode(([
  4326.                     'message' => 'Error, no timestamp found at this time',
  4327.                     'path' => 'src/Controller/RdvController.php',
  4328.                     "status" => 400,
  4329.                 ])), 400);
  4330.             }
  4331.         } else {
  4332.             if ($publicFunction->calculScheduleFitDate($audio, $date, $audioMotif->getDuration(), $centre , null) == true) {
  4333.                 return new Response(json_encode(([
  4334.                     'message' => 'Error, no timestamp found at this time',
  4335.                     'path' => 'src/Controller/RdvController.php',
  4336.                     "status" => 400,
  4337.                 ])), 400);
  4338.             }
  4339.         }*/
  4340.         $rdv->setDate($date);
  4341.         $rdv->setDateCreation(\DateTime::createFromFormat("d/m/Y H:i"date('d/m/Y H:i')));
  4342.         /** @var EtatRdv */
  4343.         $etat $this->getDoctrine()
  4344.             ->getRepository(EtatRdv::class)
  4345.             ->findOneBy(['id' => $data["etat_id"]]);
  4346.         if ($etat == null) {
  4347.             return new Response(json_encode(([
  4348.                 'message' => 'Error, no etat found at this id',
  4349.                 'path' => 'src/Controller/RdvController.php',
  4350.                 "status" => 400,
  4351.             ])), 400);
  4352.         }
  4353.         $rdv->setIdEtat($etat);
  4354.         $rdv->setIdMotif($motif);
  4355.         $rdv->setDuration($data["duree"]);
  4356.         $rdv->setIsAbsence($data["is_absence"]);
  4357.         $entityManager $this->getDoctrine()->getManager();
  4358.         $entityManager->persist($rdv);
  4359.         $entityManager->flush();
  4360.         $date $rdv->getDate();
  4361.         $smsDate $date->format('d-m-Y H:i');
  4362.         $locale 'fr_FR';
  4363.         $formatter = new IntlDateFormatter(
  4364.             $locale,
  4365.             IntlDateFormatter::FULL,
  4366.             IntlDateFormatter::SHORT,
  4367.             null,
  4368.             IntlDateFormatter::GREGORIAN,
  4369.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  4370.         );
  4371.         $smsDateLongFormat $formatter->format($date);
  4372.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  4373.         // client notif mail Sms
  4374.         // we send parametre for the trait methid
  4375.         //$params = $this->emailNotificationService->prepareEmailParams($user);
  4376.         // send email notifcation
  4377.         //$this->emailNotificationService->sendEmail($params, 'admin@example.com', 'Nouvelle inscription à My Audio Pro', 1);
  4378.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  4379.         $frenchDate ucfirst($frenchDate);
  4380.         $params = array(
  4381.             "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  4382.             "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  4383.             "date" => $smsDateLongFormat,
  4384.             "prenom" => $client->getName(),
  4385.             //"heure" => $smsDatee,
  4386.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  4387.             "centerName" => $rdv->getIdCentre()->getName(),
  4388.             "centerAddress" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  4389.             "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  4390.             "centerCity" => $rdv->getIdCentre()->getCity(),
  4391.             "motif" => $rdv->getIdMotif()->getTitre(),
  4392.             "RdvDate" => substr($smsDate010) . " à "  substr($smsDate1115),
  4393.             "audioName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  4394.             "clientMail" => $client->getMail(),
  4395.             "clientPhone" => $client->getPhone(),
  4396.             'titre' => "Votre rendez-vous est validé le " substr($smsDate010) . " à "  substr($smsDate1115),
  4397.             "address" => $rdv->getIdCentre()->getAddress(),
  4398.             "postal" => $rdv->getIdCentre()->getPostale(),
  4399.             "city" => $rdv->getIdCentre()->getCity(),
  4400.             "clientEmail" => $client->getMail(),
  4401.             "clientPassword" => isset($data["passwordGenerated"]) ? $data["passwordGenerated"] : null,
  4402.             "clientAddress" => $client->getAddress(),
  4403.             "clientPostal" => $client->getPostal(),
  4404.             "clientCity" => $client->getCity(),
  4405.             "audioName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  4406.             "frenchDate" => $frenchDate,
  4407.             "heure" => substr($smsDate1115),
  4408.             "centerName" => $rdv->getIdCentre()->getName(),
  4409.             "audioMail" => $rdv->getIdAudio()->getMail(),
  4410.             "modifUrl" => "{$_ENV['BASE_client']}mes-rendez-vous",
  4411.         );
  4412.         $subject "Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  4413.         $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject181);
  4414.         $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.";
  4415.         // $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $client->getPhone());
  4416.         // audio Notif mail SMS
  4417.         /* $params = array(  
  4418.                         "lienModifer" =>"{$_ENV['BASE_logiciel']}rdv",
  4419.                         "lienAnnule"=> "{$_ENV['BASE_logiciel']}rdv",
  4420.                         "date" => substr($smsDate, 0, 10),
  4421.                         "heure" =>substr($smsDate, 11, 15),
  4422.                         'motif' => $rdv->getIdMotif()->getTitre(),
  4423.                         'clientPhone'=> $client->getPhone(),
  4424.                         'clientNom' =>$client->getLastname(),
  4425.                         'clientPrenom' =>$client->getName(),
  4426.                         'clientCivilite' => $client->getCivilite(),
  4427.                         'clientPostal' => $client->getPostal(),
  4428.                         'clientMail' => $client->getMail(),
  4429.                         'centerName' => $rdv->getIdCentre()->getName(),
  4430.                         'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4431.                         'centerCity' => $rdv->getIdCentre()->getCity(),
  4432.                         'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4433.                         'idPatient' => $client->getId(),
  4434.                         'proUrl' => "{$_ENV['BASE_logiciel']}",
  4435.                         'audioproName' => $rdv->getIdAudio()->getCivilite().' '.$rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(),
  4436.                         'titre' => 'Votre rendez-vous est modifié pour le :'
  4437.                     );
  4438.         $subject = "🔀 Rendez-vous My Audio modifié du ". $frenchDate . " à " . substr($smsDate, 11, 15);
  4439.         $publicFunction->sendEmail($params, $rdv->getIdAudio()->getMail(), $rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(), $subject, 186 );
  4440.         $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.";
  4441.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $rdv->getIdAudio()->getPhone());*/
  4442.         // google calendar post
  4443.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  4444.             ->findBy(array('audio' => $audio->getId()));
  4445.         $data['rdv'] = $rdv->getId();
  4446.         $synchronisationCosium $this->getDoctrine()->getRepository(SynchronisationCosium::class)->findOneBy(["audio" => $audio->getId()]);
  4447.         $cosiumCenter $this->getDoctrine()->getRepository(CosiumCenter::class)->findOneBy(["synchronisationCosium" => $synchronisationCosium"center" => $rdv->getIdCentre()]);
  4448.         if ($cosiumCenter) {
  4449.             $this->clientCosiumService->createAgenda($synchronisationCosium$rdv$cosiumCenter);
  4450.         }
  4451.         foreach ($synchronisations as $synchronisation) {
  4452.             if (!$synchronisation->getIsDeleted()) {
  4453.                 try {
  4454.                     $googleCalendar->checkAndRefreshAccessToken($synchronisation);
  4455.                     $googleCalendar->createEvent($synchronisation$data);
  4456.                 } catch (\Exception $e) {
  4457.                     error_log('Error refreshing access token or creating event: ' $e->getMessage());
  4458.                 }
  4459.             }
  4460.         }
  4461.         // create schedule notification sms
  4462.         $rdvSms->storeRdvSmsNotifications($rdv);
  4463.         if ($rdv->getClientDevice()) {
  4464.             $nextRdv $this->getDoctrine()
  4465.                 ->getRepository(Rdv::class)
  4466.                 ->find($rdv->getClientDevice()->getRdv()->getId());
  4467.             if ($nextRdv->getIdClientTemp()) {
  4468.                 $nextRdvs $this->getDoctrine()
  4469.                     ->getRepository(Rdv::class)
  4470.                     ->findBy([
  4471.                         "id_client_temp" => $nextRdv->getIdClientTemp(),
  4472.                         "id_motif" => ['106''107''108''109']
  4473.                     ]);
  4474.             } else {
  4475.                 $nextRdvs $this->getDoctrine()
  4476.                     ->getRepository(Rdv::class)
  4477.                     ->findBy([
  4478.                         "id_client" => $nextRdv->getIdClient(),
  4479.                         "id_motif" => ['106''107''108''109']
  4480.                     ]);
  4481.             }
  4482.             $mappedNextRdvs array_map(function ($rdv) {
  4483.                 return [
  4484.                     'id' => $rdv->getId(),
  4485.                     'date' => $rdv->getDate()->format('d-m-Y'),
  4486.                     'hours' => $rdv->getDate()->format('H:i'),
  4487.                     'duration' => $rdv->getDuration(),
  4488.                     "motif_id" => $rdv->getIdMotif()->getId(),
  4489.                     "motif_titre" => $rdv->getIdMotif()->getTitre(),
  4490.                     "duration" => $rdv->getDuration(),
  4491.                 ];
  4492.             }, $nextRdvs);
  4493.         }
  4494.         return new Response(json_encode(([
  4495.             "id" => $rdv->getId(),
  4496.             "motif_id" => $rdv->getIdMotif()->getId(),
  4497.             "audio_id" => $rdv->getIdAudio()->getId(),
  4498.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  4499.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  4500.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  4501.             "centerName" => $rdv->getIdCentre()->getName(),
  4502.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  4503.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  4504.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  4505.             "duration" => $data["duree"],
  4506.             "etat_id" => $rdv->getIdEtat()->getId(),
  4507.             "date" => $rdv->getDate(),
  4508.             "clientEtatId" => $client->getClientStatus() ? $client->getClientStatus()->getId() : 0,
  4509.             "isClient" => ($client instanceof Client) ? 0,
  4510.             "device" => $rdv->getClientDevice() ? [
  4511.                 "isDevice" => true,
  4512.                 "deviceID" => $rdv->getClientDevice()->getDevice()->getId(),
  4513.                 "clientDeviceID" => $rdv->getClientDevice()->getId(),
  4514.                 "deviceModel" => $rdv->getClientDevice()->getDevice()->getModel(),
  4515.                 "settingName" => $rdv->getClientDevice()->getSettingDevice()->getName(),
  4516.                 "settingDeviceId" => $rdv->getClientDevice()->getSettingDevice()->getSlug(),
  4517.                 "settingSlug" => $rdv->getClientDevice()->getSettingDevice()->getSlug(),
  4518.                 "nextRdvs" => $mappedNextRdvs
  4519.             ] : [
  4520.                 "isDevice" => false
  4521.             ],
  4522.             "comment" => $rdv->getComment(),
  4523.             "review" => $rdv->getReview(),
  4524.             "note" => $rdv->getNote(),
  4525.             "status" => 200,
  4526.         ])));
  4527.     }
  4528.     /**
  4529.      * @Route("/rdv/absence", name="postAbsenceCalendar", methods={"POST"})
  4530.      */
  4531.     public function postAbsenceCalendar(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendar): Response
  4532.     {
  4533.         $data json_decode($request->getContent(), true);
  4534.         if (!isset($data["token"])) {
  4535.             return new Response(json_encode([
  4536.                 "message" => "Pas de token n'a été spécifié",
  4537.                 "status" => 401,
  4538.             ]), 401);
  4539.         }
  4540.         $entityManager $this->getDoctrine()->getManager();
  4541.         /** @var Token */
  4542.         $token $this->getDoctrine()
  4543.             ->getRepository(Token::class)
  4544.             ->findOneBy(['token' => $data["token"]]);
  4545.         if (!$token) {
  4546.             return new Response(json_encode([
  4547.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  4548.                 "status" => 404,
  4549.             ]), 404);
  4550.         }
  4551.         // get token age
  4552.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  4553.         // if the token if older than 7 days
  4554.         if ($dateDiff->7) {
  4555.             $entityManager->remove($token);
  4556.             $entityManager->flush();
  4557.             return $this->json([
  4558.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  4559.                 'path' => 'src/Controller/ClientController.php',
  4560.                 "status" => 401,
  4561.             ], 401);
  4562.         }
  4563.         // makes the rdv
  4564.         $rdv = new Rdv();
  4565.         $audio $token->getIdAudio();
  4566.         $rdv->setIdAudio($audio);
  4567.         /** @var Centre */
  4568.         if (isset($data["centre_id"])) {
  4569.             $centre $this->getDoctrine()
  4570.                 ->getRepository(Centre::class)
  4571.                 ->findOneBy(['id' => $data["centre_id"]]);
  4572.             if ($centre == null) {
  4573.                 return new Response(json_encode(([
  4574.                     'message' => 'Error, no centre found at this id',
  4575.                     'path' => 'src/Controller/RdvController.php',
  4576.                     "status" => 400,
  4577.                 ])), 400);
  4578.             }
  4579.             /** @var AudioCentre */
  4580.             $liaison $this->getDoctrine()
  4581.                 ->getRepository(AudioCentre::class)
  4582.                 ->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
  4583.             if ($liaison == null) {
  4584.                 return new Response(json_encode(([
  4585.                     'message' => 'Error, audio isnt part of the centre',
  4586.                     'path' => 'src/Controller/RdvController.php',
  4587.                     "status" => 400,
  4588.                 ])), 400);
  4589.             }
  4590.             $rdv->setIdCentre($centre);
  4591.         } elseif (isset($data["lieu_id"]) && $audio->getIsIndie()) {
  4592.             // tries to set the lieu if it's an audio indie
  4593.             $lieu $this->getDoctrine()
  4594.                 ->getRepository(Lieu::class)
  4595.                 ->findOneBy(['id' => $data["lieu_id"], 'id_gerant' => $data["audio_id"]]);
  4596.             if ($lieu == null) {
  4597.                 return new Response(json_encode(([
  4598.                     'message' => 'Error, no lieu found at this id',
  4599.                     'path' => 'src/Controller/RdvController.php',
  4600.                     "status" => 400,
  4601.                 ])), 400);
  4602.             }
  4603.             $rdv->setIdLieu($lieu);
  4604.         } else {
  4605.             return new Response(json_encode(([
  4606.                 'message' => 'Error, no lieu/centre id',
  4607.                 'path' => 'src/Controller/RdvController.php',
  4608.                 "status" => 400,
  4609.             ])), 400);
  4610.         }
  4611.         // remove the taken schedule by rdv to make sure there is no overlap
  4612.         $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4613.         $rdv->setDate($date);
  4614.         $rdv->setDateCreation(\DateTime::createFromFormat("d/m/Y H:i"date('d/m/Y H:i')));
  4615.         /** @var EtatRdv */
  4616.         $etat $this->getDoctrine()
  4617.             ->getRepository(EtatRdv::class)
  4618.             ->findOneBy(['id' => $data["etat_id"]]);
  4619.         if ($etat == null) {
  4620.             return new Response(json_encode(([
  4621.                 'message' => 'Error, no etat found at this id',
  4622.                 'path' => 'src/Controller/RdvController.php',
  4623.                 "status" => 400,
  4624.             ])), 400);
  4625.         }
  4626.         $rdv->setIdEtat($etat);
  4627.         $rdv->setDuration($data["duree"]);
  4628.         $rdv->setIsAbsence($data["is_absence"]);
  4629.         $rdv->setMotifAbsence($data["motif"]);
  4630.         $rdv->setColor($data["color"]);
  4631.         $rdv->setNote($data["note"]);
  4632.         $rdv->setCacher(0);
  4633.         $entityManager $this->getDoctrine()->getManager();
  4634.         $entityManager->persist($rdv);
  4635.         $entityManager->flush();
  4636.         // create google calendar absence event
  4637.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  4638.             ->findBy(array('audio' => $audio->getId()));
  4639.         $data['rdv'] = $rdv->getId();
  4640.         $data['motif_absence'] = $rdv->getMotifAbsence() !== '' $rdv->getMotifAbsence() : "Absence";
  4641.         //        dd($data);
  4642.         foreach ($synchronisations as $synchronisation) {
  4643.             if (!$synchronisation->getIsDeleted()) {        
  4644.                 try {
  4645.                     $googleCalendar->checkAndRefreshAccessToken($synchronisation);
  4646.         
  4647.                     $googleCalendar->createAbsenceEvent($synchronisation$data);
  4648.                 } catch (\Google\Service\Exception $e) {
  4649.                     if ($e->getCode() === 403 && str_contains($e->getMessage(), 'insufficientPermissions')) {
  4650.                         error_log("Skipped synchronisation ID {$synchronisation->getId()} due to insufficient permissions.");
  4651.                         continue;
  4652.                     }
  4653.                 throw $e;
  4654.                 }
  4655.             }
  4656.         }
  4657.         
  4658.         return new Response(json_encode(([
  4659.             "id" => $rdv->getId(),
  4660.             "audio_id" => $rdv->getIdAudio()->getId(),
  4661.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  4662.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  4663.             "duration" => $data["duree"],
  4664.             "etat_id" => $rdv->getIdEtat()->getId(),
  4665.             "date" => $rdv->getDate(),
  4666.             "status" => 200,
  4667.         ])));
  4668.     }
  4669.     /**
  4670.      * @Route("/rdv/{id}/absence", name="puttAbsenceCalendar", methods={"PUT"})
  4671.      */
  4672.     public function putAbsenceCalendar(Request $requestRdv $rdvPublicFunction $publicFunctionGoogleCalendarService $googleCalendar): Response
  4673.     {
  4674.         $data json_decode($request->getContent(), true);
  4675.         if (!isset($data["token"])) {
  4676.             return new Response(json_encode([
  4677.                 "message" => "Pas de token n'a été spécifié",
  4678.                 "status" => 401,
  4679.             ]), 401);
  4680.         }
  4681.         $entityManager $this->getDoctrine()->getManager();
  4682.         /** @var Token */
  4683.         $token $this->getDoctrine()
  4684.             ->getRepository(Token::class)
  4685.             ->findOneBy(['token' => $data["token"]]);
  4686.         if (!$token) {
  4687.             return new Response(json_encode([
  4688.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  4689.                 "status" => 404,
  4690.             ]), 404);
  4691.         }
  4692.         // get token age
  4693.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  4694.         // if the token if older than 7 days
  4695.         if ($dateDiff->7) {
  4696.             $entityManager->remove($token);
  4697.             $entityManager->flush();
  4698.             return $this->json([
  4699.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  4700.                 'path' => 'src/Controller/ClientController.php',
  4701.                 "status" => 401,
  4702.             ], 401);
  4703.         }
  4704.         // remove the taken schedule by rdv to make sure there is no overlap
  4705.         if (isset($data["date"])) {
  4706.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4707.             $rdv->setDate($date);
  4708.         }
  4709.         if (isset($data["duree"])) {
  4710.             $rdv->setDuration($data["duree"]);
  4711.         }
  4712.         if (isset($data["motif"])) {
  4713.             $rdv->setMotifAbsence($data["motif"]);
  4714.         }
  4715.         if (isset($data["color"])) {
  4716.             $rdv->setColor($data["color"]);
  4717.         }
  4718.         if (isset($data["note"])) {
  4719.             $rdv->setNote($data["note"]);
  4720.         }
  4721.         $entityManager $this->getDoctrine()->getManager();
  4722.         $entityManager->flush();
  4723.         $data['rdv'] = $rdv->getId();
  4724.         $data['motif_absence'] = $rdv->getMotifAbsence() !== '' $rdv->getMotifAbsence() : "Absence";
  4725.         $data['note'] = $rdv->getNote();
  4726.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  4727.             ->findBy(array('rdv' => $rdv));
  4728.         foreach ($rdvEvents as $rdvEvent) {
  4729.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  4730.             $googleCalendar->updateAbsenceEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
  4731.         }
  4732.         return new Response(json_encode(([
  4733.             "id" => $rdv->getId(),
  4734.             "audio_id" => $rdv->getIdAudio()->getId(),
  4735.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  4736.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  4737.             "duration" => $rdv->getDuration(),
  4738.             "etat_id" => $rdv->getIdEtat()->getId(),
  4739.             "date" => $rdv->getDate(),
  4740.             "status" => 200,
  4741.         ])));
  4742.     }
  4743.     /**
  4744.      * @Route("/rdv/{id}/calendar", name="editRdvCalendarByID", methods={"PUT"})
  4745.      */
  4746.     public function editRdvCalendarByID(SmsHandler $smsHandlerRdv $rdvRequest $requestGoogleCalendarService $googleCalendarPublicFunction $publicFunctionRdvSmsService $rdvSms): Response
  4747.     {
  4748.         $pastDate $rdv->getDate();
  4749.         $data json_decode($request->getContent(), true);
  4750.         $entityManager $this->getDoctrine()->getManager();
  4751.         if (!isset($data["token"])) {
  4752.             return new Response(json_encode([
  4753.                 "message" => "Pas de token n'a été spécifié",
  4754.                 "status" => 401,
  4755.             ]), 401);
  4756.         }
  4757.         /** @var Token */
  4758.         $token $this->getDoctrine()
  4759.             ->getRepository(Token::class)
  4760.             ->findOneBy(['token' => $data["token"]]);
  4761.         if (!$token) {
  4762.             return new Response(json_encode([
  4763.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  4764.                 "status" => 404,
  4765.             ]), 404);
  4766.         }
  4767.         // get token age
  4768.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  4769.         // if the token if older than 7 days
  4770.         if ($dateDiff->7) {
  4771.             $entityManager->remove($token);
  4772.             $entityManager->flush();
  4773.             return $this->json([
  4774.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  4775.                 'path' => 'src/Controller/ClientController.php',
  4776.                 "status" => 401,
  4777.             ], 401);
  4778.         }
  4779.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  4780.             return new Response(json_encode([
  4781.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  4782.                 "status" => 404,
  4783.             ]), 404);
  4784.         }
  4785.         if (isset($data["etat_id"])) {
  4786.             $etat $this->getDoctrine()
  4787.                 ->getRepository(EtatRdv::class)
  4788.                 ->findOneBy(['id' => $data["etat_id"]]);
  4789.             if ($etat == null) {
  4790.                 return new Response(json_encode(([
  4791.                     'message' => 'Error, no etat found at this id',
  4792.                     'path' => 'src/Controller/TrustedUserController.php',
  4793.                     "status" => 400,
  4794.                 ])), 400);
  4795.             }
  4796.             $rdv->setIdEtat($etat);
  4797.         }
  4798.         if (isset($data["audio_id"])) {
  4799.             $audio $this->getDoctrine()
  4800.                 ->getRepository(Audio::class)
  4801.                 ->findOneBy(['id' => $data["audio_id"]]);
  4802.             if ($audio == null) {
  4803.                 return new Response(json_encode(([
  4804.                     'message' => 'Error, no audio found at this id',
  4805.                     'path' => 'src/Controller/TrustedUserController.php',
  4806.                     "status" => 400,
  4807.                 ])), 400);
  4808.             }
  4809.             $rdv->setIdAudio($audio);
  4810.         }
  4811.         if (isset($data["motif_id"])) {
  4812.             $motif $this->getDoctrine()
  4813.                 ->getRepository(Motif::class)
  4814.                 ->find($data["motif_id"]);
  4815.             if ($motif == null) {
  4816.                 return new Response(json_encode(([
  4817.                     'message' => 'Error, no motif found at this id',
  4818.                     'path' => 'src/Controller/TrustedUserController.php',
  4819.                     "status" => 400,
  4820.                 ])), 400);
  4821.             }
  4822.             $rdv->setIdMotif($motif);
  4823.         }
  4824.         if (isset($data["client_id"])) {
  4825.             $client $this->getDoctrine()
  4826.                 ->getRepository(Client::class)
  4827.                 ->findOneBy(['id' => $data["client_id"]]);
  4828.             if ($client == null) {
  4829.                 return new Response(json_encode(([
  4830.                     'message' => 'Error, no client found at this id',
  4831.                     'path' => 'src/Controller/TrustedUserController.php',
  4832.                     "status" => 400,
  4833.                 ])), 400);
  4834.             }
  4835.             $rdv->setIdClient($client);
  4836.         }
  4837.         if (isset($data["date"])) {
  4838.             // remove the taken schedule by rdv to make sure there is no overlap
  4839.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4840.             $audioMotif $this->getDoctrine()
  4841.                 ->getRepository(AudioMotif::class)
  4842.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  4843.             if ($audioMotif == null) {
  4844.                 return new Response(json_encode(([
  4845.                     'message' => 'Error, no motif of this id found at this audio',
  4846.                     'path' => 'src/Controller/RdvController.php',
  4847.                     "status" => 400,
  4848.                 ])), 400);
  4849.             }
  4850.             if ($rdv->getIdAudio()->getIsIndie()) {
  4851.                 if ($rdv->getIdCentre()) {
  4852.                     // regular centre audio indie
  4853.                     /** @var AudioCentre */
  4854.                     $liaison $this->getDoctrine()
  4855.                         ->getRepository(AudioCentre::class)
  4856.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  4857.                     if ($liaison == null) {
  4858.                         return new Response(json_encode(([
  4859.                             'message' => 'Error, audio isnt part of the centre',
  4860.                             'path' => 'src/Controller/RdvController.php',
  4861.                             "status" => 400,
  4862.                         ])), 400);
  4863.                     }
  4864.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  4865.                         return new Response(json_encode(([
  4866.                             'message' => 'Error, no horaire found for this audio',
  4867.                             'path' => 'src/Controller/RdvController.php',
  4868.                             "status" => 400,
  4869.                         ])), 400);
  4870.                     }
  4871.                 } else {
  4872.                     // lieu audio indie
  4873.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  4874.                         return new Response(json_encode(([
  4875.                             'message' => 'Error, no horaire found for this audio',
  4876.                             'path' => 'src/Controller/RdvController.php',
  4877.                             "status" => 400,
  4878.                         ])), 400);
  4879.                     }
  4880.                 }
  4881.             } else {
  4882.                 // regular centre
  4883.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  4884.                     return new Response(json_encode(([
  4885.                         'message' => 'Error, no horaire found for this audio',
  4886.                         'path' => 'src/Controller/RdvController.php',
  4887.                         "status" => 400,
  4888.                     ])), 400);
  4889.                 }
  4890.             }
  4891.             $rdv->setDate($date);
  4892.         }
  4893.         if (isset($data["comment"]) && $token->getIdClient()) {
  4894.             $rdv->setComment($data["comment"]);
  4895.         }
  4896.         if (isset($data["review"]) && $token->getIdClient()) {
  4897.             $rdv->setReview($data["review"]);
  4898.         }
  4899.         if (isset($data["note"])) {
  4900.             $rdv->setNote($data["note"]);
  4901.         }
  4902.         $entityManager->flush();
  4903.         $date $rdv->getDate();
  4904.         $smsDate $date->format('d-m-Y H:i');
  4905.         $oldDate $pastDate->format('d-m-Y H:i');
  4906.         $locale 'fr_FR';
  4907.         $formatter = new IntlDateFormatter(
  4908.             $locale,
  4909.             IntlDateFormatter::FULL,
  4910.             IntlDateFormatter::SHORT,
  4911.             null,
  4912.             IntlDateFormatter::GREGORIAN,
  4913.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  4914.         );
  4915.         $smsDateLongFormat $formatter->format($date);
  4916.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  4917.         $frenchDate ucfirst($frenchDate);
  4918.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  4919.         // notif client
  4920.         if ($rdv->getIdEtat()->getId() != 2) {
  4921.             $params = array(
  4922.                 "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  4923.                 "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  4924.                 "date" => $smsDateLongFormat,
  4925.                 "heure" => substr($smsDate1115),
  4926.                 "motif" => $rdv->getIdMotif()->getTitre(),
  4927.                 "centerName" => $rdv->getIdCentre()->getName(),
  4928.                 "centerAddress" => $rdv->getIdCentre()->getAddress(),
  4929.                 "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  4930.                 "audioMail" => $rdv->getIdAudio()->getMail(),
  4931.                 "centerPhone" => $rdv->getIdCentre()->getPhone(),
  4932.                 "centerCity" => $rdv->getIdCentre()->getCity(),
  4933.                 "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  4934.                 'titre' => 'Votre rendez-vous est modifié pour le',
  4935.                 'frenchDate' => $frenchDate,
  4936.             );
  4937.             $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  4938.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject184);
  4939.             if ($data["sms"]) {
  4940.                 $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.";
  4941.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  4942.             }
  4943.         }
  4944.         //     //// == suppression
  4945.         else if ($rdv->getIdEtat()->getId() == 2) {
  4946.             $params = array(
  4947.                 "date" => substr($smsDate010),
  4948.                 "lien" => "{$_ENV['BASE_client']}search",
  4949.                 "heure" => substr($smsDate1115),
  4950.                 "patientName" => $client->getLastName(),
  4951.                 'titre' => 'Votre rendez-vous est annulé :',
  4952.                 'centerName' => $rdv->getIdCentre()->getName(),
  4953.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4954.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  4955.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4956.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  4957.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  4958.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  4959.                 'motif' => $rdv->getIdMotif()->getTitre(),
  4960.             );
  4961.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  4962.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject188);
  4963.             if ($data["sms"]) {
  4964.                 $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  4965.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  4966.             }
  4967.         }
  4968.         //notif Audio
  4969.         if ($rdv->getIdEtat()->getId() != 2) {
  4970.             if ($data["sms"]) {
  4971.                 $params = array(
  4972.                     "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  4973.                     "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  4974.                     "date" => substr($smsDate010),
  4975.                     "frenchDate" => $frenchDate,
  4976.                     "heure" => substr($smsDate1115),
  4977.                     'motif' => $rdv->getIdMotif()->getTitre(),
  4978.                     'clientPhone' => $client->getPhone(),
  4979.                     'clientNom' => $client->getLastname(),
  4980.                     'clientPrenom' => $client->getName(),
  4981.                     'clientCivilite' => $client->getCivilite(),
  4982.                     'clientPostal' => $client->getPostal(),
  4983.                     'clientMail' => $client->getMail(),
  4984.                     'centerName' => $rdv->getIdCentre()->getName(),
  4985.                     'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4986.                     'centerCity' => $rdv->getIdCentre()->getCity(),
  4987.                     'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4988.                     'idPatient' => $client->getId(),
  4989.                     'proUrl' => "{$_ENV['BASE_logiciel']}",
  4990.                     'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  4991.                     'titre' => 'Votre rendez-vous est modifié pour le :'
  4992.                 );
  4993.                 $subject "🔀 Rendez-vous My Audio modifié du " $frenchDate " à " substr($smsDate1115);
  4994.                 $publicFunction->sendEmail($params$rdv->getIdAudio()->getMail(), $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject186);
  4995.                 $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.";
  4996.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$rdv->getIdAudio()->getPhone());
  4997.             }
  4998.         } else if ($rdv->getIdEtat()->getId() == 2) {
  4999.             if ($data["sms"]) {
  5000.                 $params = array(
  5001.                     "date" => substr($smsDate010),
  5002.                     "lien" => "{$_ENV['BASE_client']}search",
  5003.                     "heure" => substr($smsDate1115),
  5004.                     "patientName" => $client->getLastName(),
  5005.                     'titre' => 'Votre rendez-vous est annulé :',
  5006.                     'centerName' => $rdv->getIdCentre()->getName(),
  5007.                     'centerPostal' => $rdv->getIdCentre()->getPostale(),
  5008.                     'centerCity' => $rdv->getIdCentre()->getCity(),
  5009.                     'centerAddress' => $rdv->getIdCentre()->getAddress(),
  5010.                     'centerPhone' => $rdv->getIdCentre()->getPhone(),
  5011.                     'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  5012.                     'audioMail' => $rdv->getIdAudio()->getMail(),
  5013.                     'motif' => $rdv->getIdMotif()->getTitre(),
  5014.                 );
  5015.                 $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  5016.                 $publicFunction->sendEmail($params$rdv->getIdAudio()->getMail(), $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject188);
  5017.                 $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.";
  5018.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$rdv->getIdAudio()->getPhone());
  5019.             }
  5020.         }
  5021.         /* generate sms notif on update */
  5022.         // update sms notification     
  5023.         $rdvSms->updateRdvSms($rdv);
  5024.         // google calendar update
  5025.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  5026.             ->findBy(array('audio' => $rdv->getIdAudio()));
  5027.         $data['rdv'] = $rdv->getId();
  5028.         $data['motif_id'] = $rdv->getIdMotif();
  5029.         $data['note'] = $rdv->getNote();
  5030.         if ($rdv->getIdClient() !== null) {
  5031.             $data["client_id"] = $rdv->getIdClient()->getId();
  5032.         }
  5033.         if ($rdv->getIdClientTemp() !== null) {
  5034.             $data["client_id_temp"] = $rdv->getIdClientTemp()->getId();
  5035.         }
  5036.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  5037.             ->findBy(array('rdv' => $rdv));
  5038.         foreach ($rdvEvents as $rdvEvent) {
  5039.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  5040.             $googleCalendar->updateEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
  5041.         }
  5042.         return new Response(json_encode(([
  5043.             "id" => $rdv->getId(),
  5044.             "motif_id" => $rdv->getIdMotif()->getId(),
  5045.             "audio_id" => $rdv->getIdAudio()->getId(),
  5046.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  5047.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  5048.             "fullName" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  5049.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  5050.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  5051.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  5052.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  5053.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  5054.             "centre_id" => $rdv->getIdCentre()->getId(),
  5055.             "centerName" => $rdv->getIdCentre()->getName(),
  5056.             "etat_id" => $rdv->getIdEtat()->getId(),
  5057.             "date" => $rdv->getDate(),
  5058.             "comment" => $rdv->getComment(),
  5059.             "note" => $rdv->getNote(),
  5060.             "review" => $rdv->getReview(),
  5061.             "status" => 200,
  5062.         ])));
  5063.     }
  5064.     /**
  5065.      * @Route("/rdv/{id}/absence", name="deletetAbsenceCalendar", methods={"DELETE"})
  5066.      */
  5067.     public function deletetAbsenceCalendar(Request $requestRdv $rdvGoogleCalendarService $googleCalendar): Response
  5068.     {
  5069.         $data json_decode($request->getContent(), true);
  5070.         if (!isset($data["token"])) {
  5071.             return new Response(json_encode([
  5072.                 "message" => "Pas de token n'a été spécifié",
  5073.                 "status" => 401,
  5074.             ]), 401);
  5075.         }
  5076.         $entityManager $this->getDoctrine()->getManager();
  5077.         /** @var Token */
  5078.         $token $this->getDoctrine()
  5079.             ->getRepository(Token::class)
  5080.             ->findOneBy(['token' => $data["token"]]);
  5081.         if (!$token) {
  5082.             return new Response(json_encode([
  5083.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  5084.                 "status" => 404,
  5085.             ]), 404);
  5086.         }
  5087.         // get token age
  5088.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  5089.         // if the token if older than 7 days
  5090.         if ($dateDiff->7) {
  5091.             $entityManager->remove($token);
  5092.             $entityManager->flush();
  5093.             return $this->json([
  5094.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  5095.                 'path' => 'src/Controller/ClientController.php',
  5096.                 "status" => 401,
  5097.             ], 401);
  5098.         }
  5099.         // delete google agenda event
  5100.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  5101.             ->findBy(array('rdv' => $rdv));
  5102.         //dd($rdvEvents);
  5103.         foreach ($rdvEvents as $rdvEvent) {
  5104.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  5105.             $googleCalendar->deleteEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId());
  5106.             $entityManager->remove($rdvEvent);
  5107.             $entityManager->flush();
  5108.         }
  5109.         $entityManager->remove($rdv);
  5110.         $entityManager->flush();
  5111.         return new Response(json_encode(([
  5112.             "message" => "Absence Supprime",
  5113.             "status" => 200,
  5114.         ])));
  5115.     }
  5116.     /**
  5117.      * @Route("/rdvs/facturation/rdv", name="getMyRDV", methods={"GET"})
  5118.      */
  5119.     public function getMyRDV(Request $request): Response
  5120.     {
  5121.         /* $date = new DateTime();
  5122.         $minutes_to_add = 10;
  5123.         $date->add(new DateInterval('PT' . $minutes_to_add . 'M'));
  5124.         $date->setTimezone(new DateTimeZone('Europe/Paris'));
  5125.         $currentDate = $date->format('Y-m-d H:i:00');
  5126.         $toSend = $this->getDoctrine()->getRepository(Rdv::class)
  5127.             ->findRdvsIn10Mins($currentDate); 
  5128.         */
  5129.     }
  5130.     /**
  5131.      * @Route("/rdvs/facturation/lead", name="getMyLead", methods={"GET"})
  5132.      */
  5133.     public function getMyLead(Request $request): Response {}
  5134.     /**
  5135.      * @Route("/rdvs/total-count", name="getRdvCount", methods={"GET"})
  5136.      */
  5137.     public function getRdvCount(Request $request): Response
  5138.     {
  5139.         $rdvs $this->getDoctrine()->getRepository(Rdv::class)->findAll();
  5140.         return new Response(count($rdvs));
  5141.     }
  5142.     /**
  5143.      * @Route("/admin/update-relance/{id}", name="admin_update_relance", methods={"POST"})
  5144.      */
  5145.     public function updateRelance(Request $requestLeadRdv $leadEntityManagerInterface $em): JsonResponse
  5146.     {
  5147.         $data json_decode($request->getContent(), true);
  5148.         $relanceCount $data['relanceCount'] ?? null;
  5149.         if ($relanceCount !== null) {
  5150.             $lead->setRelanceCallCount((int)$relanceCount);
  5151.             $em->flush();
  5152.             return new JsonResponse(['success' => true]);
  5153.         }
  5154.         return new JsonResponse(['success' => false], 400);
  5155.     }
  5156.     /**
  5157.      * @Route("/rdv/lead", name="postLeadRdv", methods={"POST"})
  5158.      */
  5159.     public function postLeadRdv(Request $requestEntityManagerInterface $entityManagerPublicFunction $publicFunctionGoogleCalendarService $googleCalendar): Response
  5160.     {
  5161.         $data json_decode($request->getContent(), true);
  5162.         $today = new DateTime();
  5163.         try {
  5164.             $client null;
  5165.             // Gestion du client via token ou création
  5166.             if (!empty($data['clientToken'])) {
  5167.                 $token $entityManager->getRepository(Token::class)->findOneBy(['token' => $data['clientToken']]);
  5168.                 $client $token $token->getIdClient() : null;
  5169.             } elseif (!empty($data['client'])) {
  5170.                 $clientData $this->createOrGetClient($data['client']);
  5171.                 $client $entityManager->getRepository(Client::class)->find($clientData['id']);
  5172.             }
  5173.             if (!$client) {
  5174.                 return $this->json(["status" => 400"message" => "Client non trouvé ou invalide"], 400);
  5175.             }
  5176.             // Création du rendez-vous LeadRdv
  5177.             $rdvLead = new LeadRdv();
  5178.             $rdvLead->setClient($client);
  5179.             if (isset($data['titleLead'])) {
  5180.                 $rdvLead->setTitleLead($data['titleLead']);
  5181.             }
  5182.             if (isset($data['rangeAge'])) {
  5183.                 $rdvLead->setRangeAge($data['rangeAge']);
  5184.             }
  5185.             if (isset($data['situations'])) {
  5186.                 $rdvLead->setSituationsGene($data['situations']);
  5187.             }
  5188.             if (isset($data['equipe'])) {
  5189.                 $rdvLead->setEquipeAppareil($data['equipe']);
  5190.             }
  5191.             if (isset($data['durationEquipe'])) {
  5192.                 $rdvLead->setDurationEquipeAppareil($data['durationEquipe']);
  5193.             }
  5194.             if (isset($data['bilanAuditif'])) {
  5195.                 $rdvLead->setBilanAuditif($data['bilanAuditif']);
  5196.             }
  5197.             if (isset($data['ordonance'])) {
  5198.                 $rdvLead->setOrdonance($data['ordonance']);
  5199.             }
  5200.             if (isset($data['dateOrdonance'])) {
  5201.                 $rdvLead->setDateOrdonance($data['dateOrdonance']);
  5202.             }
  5203.             if (isset($data['canMove'])) {
  5204.                 $rdvLead->setCanMove($data['canMove']);
  5205.             }
  5206.             if (isset($data['traffic_source'])) {
  5207.                 $rdvLead->setTrafficSource($data['traffic_source']);
  5208.             }
  5209.             if (isset($data['article_name'])) {
  5210.                 $rdvLead->setTrafficLpVersion($data['article_name']);
  5211.             }
  5212.             if (isset($data['lp_version'])) {
  5213.                 $rdvLead->setTrafficArticleName($data['lp_version']);
  5214.             }
  5215.             if (isset($data['isNewLp'])) {
  5216.                 $rdvLead->setIsNewLp($data['isNewLp']);
  5217.                 $leadStatus $entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'demande_contact']);
  5218.                 if ($leadStatus) {
  5219.                     $rdvLead->setLeadStatus($leadStatus);
  5220.                 }
  5221.             }
  5222.             $rdvLead->setDate($today);
  5223.             if (!empty($data['audio'])) {
  5224.                 $audio $entityManager->getRepository(Audio::class)->find($data['audio']);
  5225.                 if ($audio) {
  5226.                     $rdvLead->setAudio($audio);
  5227.                 }
  5228.             }
  5229.             if ($client->getPostal()) {
  5230.                 $centerCount $this->getMatchingCentresCount($client->getPostal());
  5231.                 $rdvLead->setCentersCount($centerCount);
  5232.                 if ($centerCount == 0) {
  5233.                     $leadStatus $entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'hors_zone']);
  5234.                     if ($leadStatus) {
  5235.                         $rdvLead->setLeadStatus($leadStatus);
  5236.                     }
  5237.                 }
  5238.             }
  5239.             // Création du Token
  5240.             $tokenString $publicFunction->generateRandomString(30);
  5241.             $token = (new Token())
  5242.                 ->setCreationDate(new DateTime())
  5243.                 ->setToken($tokenString)
  5244.                 ->setIdClient($client);
  5245.             $entityManager->persist($rdvLead);
  5246.             $entityManager->persist($token);
  5247.             $entityManager->flush();
  5248.             return $this->json([
  5249.                 "id" => $client->getId(),
  5250.                 "idRdvLead" => $rdvLead->getId(),
  5251.                 "name" => $client->getName(),
  5252.                 "lastname" => $client->getLastname(),
  5253.                 "token" => $tokenString,
  5254.                 "code" => $clientData['password'],
  5255.                 "postalCode" => $client->getPostal() ?? null,
  5256.                 "status" => 200,
  5257.             ]);
  5258.         } catch (\Exception $e) {
  5259.             return $this->json(["status" => 500"message" => $e->getMessage()], 500);
  5260.         }
  5261.     }
  5262.     /**
  5263.      * @Route("/lead/new/test", name="postLeadRdv_test", methods={"GET", "POST"})
  5264.      */
  5265.     /* public function newLead(
  5266.         ElevenLabsService $elevenLabs,
  5267.         TwilioService $twilio
  5268.     ): Response {
  5269.         $leadPhone = '+33611879183';
  5270.         $aircallRedirect = '+33743393532';
  5271.         $audioPath = $this->getParameter('kernel.project_dir') . '/public/assets/audio/message-client.mp3';
  5272.         if (!file_exists($audioPath)) {
  5273.             $elevenLabs->generateVoice(
  5274.                 "Bonjour ! Suite à votre demande, un expert va vous rappeler dans quelques instants pour répondre à votre besoin. Restez disponible, l’appel va commencer !",
  5275.                 $audioPath
  5276.             );
  5277.         }
  5278.         $twilio->callLead($leadPhone, "https://fed6-2a01-cb1d-3ac-ef00-9414-9245-af3d-ef55.ngrok-free.app/twilio/message", $aircallRedirect);
  5279.         return new Response('Lead traité, appel lancé.');
  5280.     }
  5281.         */
  5282.     /**
  5283.      * @Route("/twilio/message", name="twilio_message", methods={"GET", "POST"})
  5284.      */
  5285.     /*
  5286.     public function message(): Response
  5287.     {
  5288.         $forwardTo = $_GET['forwardTo'] ?? '';
  5289.         $twiml = <<<XML
  5290.         <?xml version="1.0" encoding="UTF-8"?>
  5291.         <Response>
  5292.             <Play>https://fed6-2a01-cb1d-3ac-ef00-9414-9245-af3d-ef55.ngrok-free.app/assets/audio/message-client.mp3</Play>
  5293.             <Dial timeout="20">{$forwardTo}
  5294.             </Dial>
  5295.         </Response>
  5296.         XML;
  5297.         return new Response($twiml, 200, ['Content-Type' => 'text/xml']);
  5298.     }
  5299.         */
  5300.     /**
  5301.      * Private method to create a new client or get existing one by phone
  5302.      */
  5303.     private function createOrGetClient(array $data): array
  5304.     {
  5305.         $clientRepository $this->entityManager->getRepository(Client::class);
  5306.         // check sur le mail et phone
  5307.         $existingClient $clientRepository->findOneBy(['mail' => $data['email']]);
  5308.         if ($existingClient) {
  5309.             if ($existingClient->getPostal() !== $data['postalCode']) {
  5310.                 $existingClient->setPostal($data['postalCode']);
  5311.                 $this->entityManager->persist($existingClient);
  5312.                 $this->entityManager->flush();
  5313.             }
  5314.             return ['id' => $existingClient->getId(), 'password' => 'Votre mot de passe'];
  5315.         }
  5316.         $randomPassword $this->generateRandomPassword(12);
  5317.         $client = new Client();
  5318.         $client->setLastname($data['lastname']);
  5319.         $client->setBirthdate(null);
  5320.         $client->setName($data['firstname']);
  5321.         $client->setPhone($data['phone']);
  5322.         $client->setMail($data['email']);
  5323.         $client->setSignupDate(new \DateTime());
  5324.         $client->setPassword(password_hash($randomPasswordPASSWORD_DEFAULT));
  5325.         $client->setPostal($data['postalCode']);
  5326.         $client->setAddress($data['address'] ?? null);
  5327.         $client->setCity($data['city'] ?? null);
  5328.         $client->setDesactivate(false);
  5329.         if (isset($data['civilite'])) {
  5330.             $civilite = ($data['civilite'] === 'Homme') ? 'Monsieur' 'Madame';
  5331.             $client->setCivilite($civilite);
  5332.         }
  5333.         $this->entityManager->persist($client);
  5334.         $this->entityManager->flush();
  5335.         return ['id' => $client->getId(), 'password' => $randomPassword];
  5336.     }
  5337.     private function generateRandomPassword($length 10): string
  5338.     {
  5339.         return bin2hex(random_bytes($length 2));
  5340.     }
  5341.     private function getMatchingCentresCount($clientPostal): int
  5342.     {
  5343.         // Récupérer les coordonnées GPS du code postal du client
  5344.         $clientCoordinates $this->entityManager
  5345.             ->getRepository(RegionDepartment::class)
  5346.             ->findOneBy(['codePostal' => $clientPostal]);
  5347.         $clientLat $clientCoordinates $clientCoordinates->getLatitude() : null;
  5348.         $clientLon $clientCoordinates $clientCoordinates->getLongitude() : null;
  5349.         $centres $this->entityManager->getRepository(Centre::class)->findAll();
  5350.         $count 0;
  5351.         foreach ($centres as $centre) {
  5352.             if ($centre->getZoneKm()) {
  5353.                 $latitude $centre->getLatitude();
  5354.                 $longitude $centre->getLongitude();
  5355.                 $radius $centre->getZoneKm();
  5356.                 $postals $this->entityManager->getRepository(RegionDepartment::class)->findPostalsWithinRadius($latitude$longitude$radius);
  5357.                 $postalCodes array_values(array_unique(array_column($postals'code_postal')));
  5358.                 if (in_array($clientPostal$postalCodes)) {
  5359.                     $count++;
  5360.                 }
  5361.             }
  5362.         }
  5363.         return $count;
  5364.     }
  5365.     /**
  5366.      * @Route("/rdv/send-map", name="getRdvMap", methods={"POST"})
  5367.      */
  5368.     public function sendEmailWithMap(Request $requestPublicFunction $publicFunction): Response
  5369.     {
  5370.         $data json_decode($request->getContent(), true);
  5371.         $mail "";
  5372.         $name "";
  5373.         $centre "";
  5374.         if (isset($data['clientToken'])) {
  5375.             $token $this->getDoctrine()->getRepository(Token::class)->findOneBy(['token' => $data['clientToken']]);
  5376.             $client $token->getIdClient();
  5377.             $mail $client->getMail();
  5378.             $name $client->getLastname() . " " $client->getName();
  5379.             $centre $this->getDoctrine()->getRepository(Centre::class)->findOneBy(['id' => $data['centre']['id']]);
  5380.         } else {
  5381.             $mail $data['email'];
  5382.             $name $data['name'];
  5383.         }
  5384.         $locale 'fr_FR';
  5385.         $dateTime DateTime::createFromFormat('d/m/Y H:i'$data['date']);
  5386.         if ($dateTime) {
  5387.             $fmt = new IntlDateFormatter($localeIntlDateFormatter::FULLIntlDateFormatter::NONE);
  5388.             $fmt->setPattern("EEEE dd MMMM");
  5389.             $formattedDate ucfirst($fmt->format($dateTime));
  5390.         } else {
  5391.             $formattedDate "Date invalide";
  5392.         }
  5393.         $params = [
  5394.             'date' => $data['date'],
  5395.             'time' => $data['time'],
  5396.             'frenchDate' => $formattedDate,
  5397.             'clientAddress' => $data['address'],
  5398.             'centerName' => $centre->getName(),
  5399.             'centerAddress' => $centre->getAddress(),
  5400.             'centerPostal' => $centre->getPostale(),
  5401.             'centerCity' => $centre->getCity(),
  5402.             'start' => $data['start'],
  5403.             'end' => $data['end'],
  5404.             'urlApi' => "{$_ENV['BASE_client']}",
  5405.         ];
  5406.         $publicFunction->sendEmail($params$mail$name"Votre Rendez-vous My Audio"198);
  5407.         return new Response(json_encode([
  5408.             "status" => 200,
  5409.             "params" => $params,
  5410.         ]), 200, ['Content-Type' => 'application/json']);
  5411.     }
  5412.     /**
  5413.      * @Route("/rdv/cantmove", name="notifCantMove", methods={"POST"})
  5414.      */
  5415.     public function notifCantMove(Request $requestPublicFunction $publicFunction): Response
  5416.     {
  5417.         $data json_decode($request->getContent(), true);
  5418.         $email "lead.myaudio@gmail.com";
  5419.         $centre "";
  5420.         $type "My Audio";
  5421.         $details "";
  5422.         $picto "❌";
  5423.         $ordo "sans ordo";
  5424.         $subject "";
  5425.         if (isset($data['ordonance'])) {
  5426.             if ($data["ordonance"] == "oui") {
  5427.                 $ordo "avec ordo";
  5428.             }
  5429.         } else {
  5430.             $ordo "";
  5431.         }
  5432.         if (isset($data['centre'])) {
  5433.             $centre $data['centre'];
  5434.             $subject $picto " Lead - demande de contact ne pouvant pas se déplacer " $data['postal'] . " " $ordo;
  5435.         } else {
  5436.             $centre "";
  5437.             $type "Hors Zone";
  5438.             $details "Pas de centre dans la zone";
  5439.             $subject $picto " Lead Hors Zone " $data['postal'] . " " $ordo " ne pouvant pas se déplacer";
  5440.         }
  5441.         $responses = [
  5442.             'rangeAge' => isset($data['rangeAge']) ? $data['rangeAge'] : null,
  5443.             'situations' => isset($data['situations']) ? $data['situations'] : null,
  5444.             'equipeAppareil' => isset($data['equipe']) ? $data['equipe'] : null,
  5445.             'durationEquipe' => isset($data['durationEquipe']) ? $data['durationEquipe'] : null,
  5446.             'bilanAuditif' => isset($data['bilanAuditif']) ? $data['bilanAuditif'] : null,
  5447.             'ordonance' => isset($data['ordonance']) ? $data['ordonance'] : null,
  5448.             'dateOrdonance' => isset($data['dateOrdonance']) ? $data['dateOrdonance'] : null,
  5449.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  5450.         ];
  5451.         $department $this->getDepartmentFromPostalCode($data['address']);
  5452.         $data['departmentCode'] = $department['departmentCode'];
  5453.         $data['departmentName'] = $department['departmentName'];
  5454.         $data['regionName'] = $department['regionName'];
  5455.         $data['city'] = $department['city'];
  5456.         $params = [
  5457.             'date' => $data['date'],
  5458.             'time' => $data['time'],
  5459.             'address' => $data['address'],
  5460.             'centre' => $centre,
  5461.             'type' => $type,
  5462.             'details' => $details,
  5463.             'responses' => $responses,
  5464.             'name' => $data['name'],
  5465.             'civilite' => $data['civilite'],
  5466.             'nom' => $data['firstname'],
  5467.             'prenom' => $data['lastname'],
  5468.             'codePostal' => $data['address'],
  5469.             'telephone' => $data['phone'],
  5470.             'email' => $data['email'],
  5471.             'departement' => $data['departmentName'],
  5472.             'ville' => $data['city'],
  5473.             'region' => $data['regionName'],
  5474.             'trangeAge' => isset($data['rangAge']) ? $data['rangAge'] : null,
  5475.             'situationVecu' => isset($data['situations']) ? implode(', '$data['situations']) : null,
  5476.             'dejaEquipe' => isset($data['equipeAppareil']) ? $data['equipeAppareil'] : null,
  5477.             'trafficSource' => isset($data['traffic_source']) ? $data['traffic_source'] : null,
  5478.             'articleName' => isset($data['article_name']) ? $data['article_name'] : null,
  5479.             'lpVersion' => isset($data['lp_version']) ? $data['lp_version'] : null,
  5480.         ];
  5481.         $publicFunction->sendEmail($params$email$data['name'], $subject208);
  5482.         return new Response(json_encode([
  5483.             "status" => 200,
  5484.         ]), 200, ['Content-Type' => 'application/json']);
  5485.     }
  5486.     /**
  5487.      * @Route("/rdv/cantmove/v2", name="notifCantMoveV2", methods={"POST"})
  5488.      */
  5489.     public function notifCantMoveV2(Request $requestPublicFunction $publicFunction): Response
  5490.     {
  5491.         $data json_decode($request->getContent(), true);
  5492.         $email "lead.myaudio@gmail.com";
  5493.         $centre "";
  5494.         $type "My Audio";
  5495.         $details "";
  5496.         $picto "❌";
  5497.         $subject "";
  5498.         $audio "";
  5499.         $subject $picto " Lead ne pouvant pas se déplacer";
  5500.         $department $this->getDepartmentFromPostalCode($data['address']);
  5501.         $data['departmentCode'] = $department['departmentCode'];
  5502.         $data['departmentName'] = $department['departmentName'];
  5503.         $data['regionName'] = $department['regionName'];
  5504.         $data['city'] = $department['city'];
  5505.         $password "";
  5506.         $params = [
  5507.             'name' => $data['name'],
  5508.             'civilite' => $data['civilite'],
  5509.             'nom' => $data['firstname'],
  5510.             'prenom' => $data['lastname'],
  5511.             'codePostal' => $data['address'],
  5512.             'telephone' => $data['phone'],
  5513.             'email' => $data['email'],
  5514.             'password' => $data['clientSecretCookie'],
  5515.             'trancheAge' => isset($data['rangAge']) ? $data['rangAge'] : null,
  5516.             'situationVecu' => isset($data['situations']) ? implode(', '$data['situations']) : null,
  5517.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  5518.             'trafficSource' => isset($data['traffic_source']) ? $data['traffic_source'] : null,
  5519.             'articleName' => isset($data['article_name']) ? $data['article_name'] : null,
  5520.             'lpVersion' => isset($data['lp_version']) ? $data['lp_version'] : null,
  5521.             'urlLogin' => "{$_ENV['BASE_client']}login"
  5522.         ];
  5523.         // Send email to MyAudio
  5524.         $publicFunction->sendEmail($params$email$data['name'], $subject220);
  5525.         $publicFunction->sendEmail($params'mickael.aubard@myaudio.fr"'$data['name'], $subject220);
  5526.         // Send email to patient
  5527.         $params = [
  5528.             'clientEmail' => $data['email'],
  5529.             'clientPassword' => $data['clientSecretCookie'],
  5530.             'rdv' => "https://www.myaudio.fr/search",
  5531.             'urlLogin' => "{$_ENV['BASE_client']}login"
  5532.         ];
  5533.         $publicFunction->sendEmail($params$data['email'], $data['name'], 'Rendez-vous My Audio - En cours de traitement'219);
  5534.         $rdvLead $this->entityManager->getRepository(LeadRdv::class)->find($data['clientRdvLp']);
  5535.         if ($rdvLead) {
  5536.             $leadStatus $this->entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'cant_move']);
  5537.             if ($leadStatus) {
  5538.                 $rdvLead->setLeadStatus($leadStatus);
  5539.                 $this->entityManager->flush();
  5540.             }
  5541.         }
  5542.         return new Response(json_encode([
  5543.             "status" => 200,
  5544.         ]), 200, ['Content-Type' => 'application/json']);
  5545.     }
  5546.     /**
  5547.      * @Route("/rdv/notiflead", name="notifLead", methods={"POST"})
  5548.      */
  5549.     public function notifLeadRdv(Request $requestPublicFunction $publicFunction): Response
  5550.     {
  5551.         $data json_decode($request->getContent(), true);
  5552.         $email "lead.myaudio@gmail.com";
  5553.         $centre "";
  5554.         $type "My Audio";
  5555.         $details "";
  5556.         $picto "❌";
  5557.         $ordo "sans ordo";
  5558.         $subject "";
  5559.         $name "";
  5560.         $postal "";
  5561.         $emailPatient "";
  5562.         if (isset($data['clientToken']) && !empty($data['clientToken'])) {
  5563.             $token $this->getDoctrine()->getRepository(Token::class)->findOneBy(['token' => $data['clientToken']]);
  5564.             $client $token->getIdClient();
  5565.             $name $client->getLastname() . " " $client->getName();
  5566.             $postal $client->getPostal();
  5567.             $emailPatient $client->getMail();
  5568.         } else {
  5569.             if (isset($data['postal'])) {
  5570.                 $postal $data['postal'];
  5571.             }
  5572.             if (isset($data['name'])) {
  5573.                 $name $data['name'];
  5574.             }
  5575.             if (isset($data['email'])) {
  5576.                 $email $data['email'];
  5577.             }
  5578.             if (isset($data['email'])) {
  5579.                 $emailPatient $data['email'];
  5580.             }
  5581.         }
  5582.         if (isset($data["ordonance"])) {
  5583.             if ($data["ordonance"] == "oui") {
  5584.                 $ordo "avec ordo";
  5585.             }
  5586.         }
  5587.         if (isset($data['centre'])) {
  5588.             $centre $data['centre'];
  5589.             $picto "✅";
  5590.             $subject $picto " Lead booké " $postal " " $ordo;
  5591.         } else {
  5592.             $centre "";
  5593.             $type "Hors Zone";
  5594.             $details "Pas de centre dans la zone";
  5595.             $subject $picto " Lead Hors Zone " $postal " " $ordo;
  5596.         }
  5597.         $responses = [
  5598.             'rangeAge' => isset($data['rangeAge']) ? $data['rangeAge'] : null,
  5599.             'situations' => isset($data['situations']) ? $data['situations'] : null,
  5600.             'equipeAppareil' => isset($data['equipe']) ? $data['equipe'] : null,
  5601.             'durationEquipe' => isset($data['durationEquipe']) ? $data['durationEquipe'] : null,
  5602.             'bilanAuditif' => isset($data['bilanAuditif']) ? $data['bilanAuditif'] : null,
  5603.             'ordonance' => isset($data['ordonance']) ? $data['ordonance'] : null,
  5604.             'dateOrdonance' => isset($data['dateOrdonance']) ? $data['dateOrdonance'] : null,
  5605.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  5606.         ];
  5607.         $params = [
  5608.             'date' => $data['date'],
  5609.             'time' => $data['time'],
  5610.             'address' => $data['address'],
  5611.             'centre' => $centre,
  5612.             'type' => $type,
  5613.             'details' => $details,
  5614.             'responses' => $responses,
  5615.             'name' => $name,
  5616.             'email' => $emailPatient,
  5617.         ];
  5618.         $publicFunction->sendEmail($params$email$name$subject180);
  5619.         return new Response(json_encode([
  5620.             "status" => 200,
  5621.             "params" => $params,
  5622.             "responses" => $responses
  5623.         ]), 200, ['Content-Type' => 'application/json']);
  5624.     }
  5625.     /**
  5626.      *  Met à jour l'état d'un rendez-vous.
  5627.      *
  5628.      * Cette fonction permet de modifier l'état d'un rendez-vous en fonction des données envoyées
  5629.      * via une requête PUT. Elle effectue plusieurs vérifications, notamment :
  5630.      * - La présence et la validité du token d'authentification.
  5631.      * - L'existence du rendez-vous et du nouvel état.
  5632.      * - L'expiration du token (plus de 7 jours).
  5633.      * 
  5634.      * Si le rendez-vous est marqué comme "Absence injustifiée" (état ID 3), un email et un SMS sont envoyés
  5635.      * au client et à l'équipe MyAudio pour les informer.
  5636.      * 
  5637.      * @Route("api/save-etat-rdv", name="saveEtatRdv", methods={"PUT"})
  5638.      */
  5639.     public function saveEtatRdv(Request $requestPublicFunction $publicFunction): Response
  5640.     {
  5641.         $entityManager $this->getDoctrine()->getManager();
  5642.         $data json_decode($request->getContent(), true);
  5643.         if (!$data['token']) {
  5644.             return new Response(json_encode([
  5645.                 "message" => "Pas de token n'a été spécifié",
  5646.                 "status" => 401,
  5647.             ]), 401);
  5648.         }
  5649.         /** @var Token */
  5650.         $token $this->getDoctrine()
  5651.             ->getRepository(Token::class)
  5652.             ->findOneBy(['token' => $data['token'], 'id_audio' => $data['audio']]);
  5653.         if (!$token) {
  5654.             return new Response(json_encode([
  5655.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  5656.                 "status" => 404,
  5657.             ]), 404);
  5658.         }
  5659.         // get token age
  5660.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  5661.         // if the token if older than 7 days
  5662.         if ($dateDiff->7) {
  5663.             $entityManager->remove($token);
  5664.             $entityManager->flush();
  5665.             return $this->json([
  5666.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  5667.                 'path' => 'src/Controller/ClientController.php',
  5668.                 "status" => 401,
  5669.             ], 401);
  5670.         }
  5671.         $rdv $this->getDoctrine()->getRepository(Rdv::class)->find($data['rdv']);
  5672.         if (!$rdv) {
  5673.             return new Response(json_encode([
  5674.                 "message" => "Rdv not found.",
  5675.                 "status" => 404,
  5676.             ]), 404);
  5677.         }
  5678.         $rdvEtat $this->getDoctrine()
  5679.             ->getRepository(EtatRdv::class)
  5680.             ->find($data['etat']);
  5681.         if (!$rdvEtat) {
  5682.             return new Response(json_encode([
  5683.                 "message" => "Rdv etat not found.",
  5684.                 "status" => 404,
  5685.             ]), 404);
  5686.         }
  5687.         $rdv->setIdEtat($rdvEtat);
  5688.         $entityManager->flush();
  5689.         $encodedNomDuCentre rawurlencode($rdv->getIdCentre()->getName());
  5690.         $urlApi "audioprothesiste/{$rdv->getIdCentre()->getCity()}/{$rdv->getIdCentre()->getPostale()}/{$encodedNomDuCentre}/prise-de-rdvaudioprothesiste-rapide/{$rdv->getIdCentre()->getId()}";
  5691.         if ($rdvEtat->getId() == 3) {
  5692.             // Send email to client
  5693.             $date $rdv->getDate();
  5694.             $smsDate $date->format('d-m-Y H:i');
  5695.             $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  5696.             $params = array(
  5697.                 "date" => substr($smsDate010),
  5698.                 "lien" => "{$_ENV['BASE_client']}$urlApi,
  5699.                 "heure" => substr($smsDate1115),
  5700.                 'centerName' => $rdv->getIdCentre()->getName() ?? '',
  5701.                 'centerPostal' => $rdv->getIdCentre()->getPostale() ?? '',
  5702.                 'centerCity' => $rdv->getIdCentre()->getCity() ?? '',
  5703.                 'centerAddress' => $rdv->getIdCentre()->getAddress() ?? '',
  5704.                 'centerPhone' => $rdv->getIdCentre()->getPhone() ?? '',
  5705.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName() ?? '',
  5706.                 'audioMail' => $rdv->getIdAudio()->getMail() ?? '',
  5707.             );
  5708.             $subject "Vous avez manqué votre rendez-vous MyAudio avec " $rdv->getIdCentre()->getName();
  5709.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject214);
  5710.             // Send sms to client
  5711.             $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();
  5712.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  5713.             // Send email to MyAudio
  5714.             $date $rdv->getDate();
  5715.             $smsDate $date->format('d-m-Y H:i');
  5716.             $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  5717.             $params = array(
  5718.                 "date" => substr($smsDate010),
  5719.                 "lien" => "{$_ENV['BASE_client']}search",
  5720.                 "heure" => substr($smsDate1115),
  5721.                 'centerName' => $rdv->getIdCentre()->getName() ?? '',
  5722.                 'centerPostal' => $rdv->getIdCentre()->getPostale() ?? '',
  5723.                 'centerCity' => $rdv->getIdCentre()->getCity() ?? '',
  5724.                 'centerAddress' => $rdv->getIdCentre()->getAddress() ?? '',
  5725.                 'centerPhone' => $rdv->getIdCentre()->getPhone() ?? '',
  5726.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName() ?? '',
  5727.                 'audioMail' => $rdv->getIdAudio()->getMail() ?? '',
  5728.                 'clientName' => $client->getName() . ' ' $client->getLastName() ?? '',
  5729.                 'clientMail' => $client->getMail() ?? '',
  5730.                 'clientPhone' => $client->getPhone() ?? '',
  5731.             );
  5732.             $subject "Le patient " $client->getName() . ' ' $client->getLastName() . " a manqué son rendez-vous MyAudio avec le centre " $rdv->getIdCentre()->getName();
  5733.             $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$client->getName() . ' ' $client->getLastName(), $subject215);
  5734.         }
  5735.         return new Response(json_encode([
  5736.             "message" => "rdvEtat has been successfully updated",
  5737.             "status" => 200,
  5738.         ]));
  5739.     }
  5740.     /**
  5741.      * 
  5742.      * @Route("api/send-email/clientnotcompletebook", name="askToContact", methods={"POST"})
  5743.      */
  5744.     public function askToContact(Request $requestPublicFunction $publicFunction): Response
  5745.     {
  5746.         $data json_decode($request->getContent(), true);
  5747.         $staticToken "3f3a8b74f3e5b2d0c4917f5f9a7c07efb1a0f1e5e8c907ec9c4e9df129e3125e9";
  5748.         $token $data['token'] ?? null;
  5749.         if ($token !== $staticToken) {
  5750.             return new JsonResponse(
  5751.                 [
  5752.                     'status' => 'error',
  5753.                     'code' => 'unauthorized',
  5754.                     'message' => 'Unauthorized access.'
  5755.                 ],
  5756.                 JsonResponse::HTTP_UNAUTHORIZED
  5757.             );
  5758.         }
  5759.         $params = [
  5760.             'clientCivilite' => isset($data['civilite']) ? $data['civilite'] : 'Pas indiqué',
  5761.             'clientNom' => isset($data['firstname']) ? $data['firstname'] : null,
  5762.             'clientPrenom' => isset($data['lastname']) ? $data['lastname'] : null,
  5763.             'clientPostal' => isset($data['postalCode']) ? $data['postalCode'] : null,
  5764.             'clientPhone' => isset($data['phone']) ? $data['phone'] : null,
  5765.             'clientMail' => isset($data['email']) ? $data['email'] : null,
  5766.             'password' => isset($data['clientSecretCookie']) ? $data['clientSecretCookie'] : null,
  5767.             'rangeAge' => isset($data['trancheAge']) ? $data['trancheAge'] : null,
  5768.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  5769.             'situations' => isset($data['situations']) ? implode(', '$data['situations']) : null,
  5770.             'trafficSource' => isset($data['traffic_source']) ? $data['traffic_source'] : null,
  5771.             'articleName' => isset($data['article_name']) ? $data['article_name'] : null,
  5772.             'lpVersion' => isset($data['lp_version']) ? $data['lp_version'] : null,
  5773.         ];
  5774.         $templateEmailMyAudio 223;
  5775.         if (!empty($data['centre'])) {
  5776.             $centre $data['centre'];
  5777.             $audio $centre['audio'][0];
  5778.             $params['centerName'] = $centre['name'] ?? null;
  5779.             $params['centerPostal'] = $centre['postale'] ?? null;
  5780.             $params['centerCity'] = $centre['city'] ?? null;
  5781.             $params['centerAddress'] = $centre['address'] ?? null;
  5782.             $params['centerPhone'] = $centre['phone'] ?? null;
  5783.             $params['audioproName'] = $audio['civilite'] . ' ' $audio['lastname'] . ' ' $audio['name'] ?? null;
  5784.             $templateEmailMyAudio 222;
  5785.         }
  5786.         // Email to My Audio
  5787.         $email "lead.myaudio@gmail.com";
  5788.         $subject "Demande de contact -  Nouveau Lead À Contacter Hors Zone";
  5789.         $publicFunction->sendEmail($params$email$data['name'], $subject$templateEmailMyAudio);
  5790.         $publicFunction->sendEmail($params'mickael.aubard@myaudio.f'$data['name'], $subject$templateEmailMyAudio);
  5791.         $coordinates $this->getCoordinatesFromPostalCode($data['postalCode']);
  5792.         $latitude $coordinates['latitude'];
  5793.         $longitude $coordinates['longitude'];
  5794.         $params = [
  5795.             'email' => isset($data['email']) ? $data['email'] : null,
  5796.             'password' => isset($data['clientSecretCookie']) ? $data['clientSecretCookie'] : null,
  5797.             "lienRdv" => "{$_ENV['BASE_client']}search?latitude={$latitude}&longitude={$longitude}&ville={$data['postalCode']}",
  5798.         ];
  5799.         // Email to Client
  5800.         $subject "My Audio - Confirmation de demande de contact";
  5801.         $publicFunction->sendEmail($params$data['email'], $data['name'], $subject221);
  5802.         $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";
  5803.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$data['phone']);
  5804.         if (isset($data['clientRdvLp'])) {
  5805.             $rdvLead $this->entityManager->getRepository(LeadRdv::class)->find($data['clientRdvLp']);
  5806.             if ($rdvLead) {
  5807.                 $rdvLead->setSendAskToContact(1);
  5808.                 $rdvLead->setCountAskToContact(($rdvLead->getCountAskToContact() ?? 0) + 1);
  5809.                 $this->entityManager->flush();
  5810.                 $this->sendWhatsApp($data$rdvLead);
  5811.             }
  5812.         }
  5813.         return new Response(json_encode([
  5814.             "message" => "Email ask for contact send with success",
  5815.             "status" => 200,
  5816.         ]));
  5817.     }
  5818.     private function sendWhatsApp($data$lead): void
  5819.     {
  5820.         $adminUrl $this->adminUrlGenerator
  5821.             ->setDashboard(DashboardController::class)
  5822.             ->setController(LeadRdvCrudController::class)
  5823.             ->setAction('detail')
  5824.             ->setEntityId($lead->getId())
  5825.             ->generateUrl();
  5826.         $relativeUrl parse_url($adminUrlPHP_URL_PATH) . '?' parse_url($adminUrlPHP_URL_QUERY);
  5827.         // Supprimer le slash en trop s’il y en a un au début
  5828.         $relativeUrl ltrim($relativeUrl'/');
  5829.         // 🧑‍🤝‍🧑 Tableau des destinataires
  5830.         $destinataires = [
  5831.             '33611879183'// Numéro 1
  5832.             '33667597626'// Numéro 2
  5833.             '447884128220'// Numéro 3
  5834.         ];
  5835.         foreach ($destinataires as $numero) {
  5836.             $this->whatsapp->sendTemplateMessage(
  5837.                 $numero,  // Numéro de téléphone du destinataire
  5838.                 'lead_notif_myaudio',  // Nom du template WhatsApp
  5839.                 [
  5840.                     'body' => [
  5841.                         ['parameter_name' => 'nom_client''text' => $data['firstname'] . ' ' $data['lastname']],  // {{nom_client}}
  5842.                         ['parameter_name' => 'email_client''text' => $data['email'] ?? ' '],  // {{email_client}}
  5843.                         ['parameter_name' => 'telephone_client''text' => $data['phone'] ?? ' '],  // {{telephone_client}}
  5844.                         ['parameter_name' => 'date_lead''text' => $lead->getDate()->format('d/m/Y H:i')],  // {{date_lead}}
  5845.                         ['parameter_name' => 'code_postal''text' => $data['postalCode'] ?? ' '],  // {{code_postal}}
  5846.                         ['parameter_name' => 'nombre_centres''text' => $lead->getCentersCount() ?? '0'],  // {{nombre_centres}}
  5847.                     ],
  5848.                     'button' => $relativeUrl,  // <--- seulement le chemin dynamique
  5849.                 ]
  5850.             );
  5851.         }
  5852.     }
  5853.     /**
  5854.      * Get coordinates from the postal code using the database.
  5855.      */
  5856.     private function getCoordinatesFromPostalCode(string $postalCode): array
  5857.     {
  5858.         $region $this->entityManager
  5859.             ->getRepository(RegionDepartment::class)
  5860.             ->findOneBy(['codePostal' => $postalCode]);
  5861.         if ($region) {
  5862.             return [
  5863.                 'latitude' => $region->getLatitude(),
  5864.                 'longitude' => $region->getLongitude(),
  5865.             ];
  5866.         }
  5867.         return [
  5868.             'latitude' => null,
  5869.             'longitude' => null,
  5870.         ];
  5871.     }
  5872.     /**
  5873.      * Get the department code from the code postal
  5874.      */
  5875.     private function getDepartmentFromPostalCode(string $postalCode): ?array
  5876.     {
  5877.         $region $this->entityManager
  5878.             ->getRepository(RegionDepartment::class)
  5879.             ->findOneBy(['codePostal' => $postalCode]);
  5880.         if ($region) {
  5881.             return [
  5882.                 'departmentCode' => $region->getCodeDepartement(),
  5883.                 'departmentName' => $region->getNomDepartement(),
  5884.                 'regionCode' => $region->getCodeRegion(),
  5885.                 'regionName' => $region->getNomRegion(),
  5886.                 'city' => $region->getNomCommunePostal(),
  5887.             ];
  5888.         }
  5889.         return null;
  5890.     }
  5891.     /**
  5892.      * 
  5893.      * @Route("/giuili-admin/lead/{leadId}/centre/{centreId}", name="showLeadCentre", methods={"GET"})
  5894.      */
  5895.     public function showLeadCentre(int $leadIdCentre $centreId): Response
  5896.     {
  5897.         // dd("tets");
  5898.         $center $centres $this->getDoctrine()
  5899.             ->getRepository(AudioCentre::class)
  5900.             ->findOneBy(['id_centre' => $centreId->getId()]);
  5901.         $audio $center->getIdAudio();
  5902.         $motifs $this->getDoctrine()->getRepository(AudioMotif::class)
  5903.             ->findBy(['id_audio' => $audio'isDeleted' => 0]);
  5904.         return $this->render('easyadmin/leadRdv/centre_show.html.twig', [
  5905.             'audio' => $audio,
  5906.             'leadId' => $leadId,
  5907.             'centreId' => $centreId,
  5908.             'motifs' => $motifs,
  5909.         ]);
  5910.     }
  5911.     /**
  5912.      * @Route("/rdv-easyadmin", name="postRdvEasyAdmin", methods={"POST"})
  5913.      */
  5914.     public function postRdvEasyAdmin(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendarRdvSmsService $rdvSms): Response
  5915.     {
  5916.         $data json_decode($request->getContent(), true);
  5917.         $entityManager $this->getDoctrine()->getManager();
  5918.         $audio $this->getDoctrine()
  5919.             ->getRepository(Audio::class)
  5920.             ->findOneBy(['id' => $data["audio_id"]]);
  5921.         $leadRdv =   $this->getDoctrine()->getRepository(LeadRdv::class)
  5922.             ->find($data["lead_id"]);
  5923.         $client $this->getDoctrine()->getRepository(Client::class)
  5924.             ->find($leadRdv->getClient());
  5925.         $responses = [
  5926.             'rangeAge' => $leadRdv->getRangeAge(),
  5927.             'situations' =>  implode(", "$leadRdv->getSituationsGene()),
  5928.             'equipeAppareil' => $leadRdv->getEquipeAppareil(),
  5929.             'durationEquipe' => $leadRdv->getDurationEquipeAppareil(),
  5930.             'bilanAuditif' => $leadRdv->getBilanAuditif(),
  5931.             'ordonance' => $leadRdv->getOrdonance(),
  5932.             'dateOrdonance' => $leadRdv->getDateOrdonance(),
  5933.             'canMove' => $leadRdv->getCanMove(),
  5934.         ];
  5935.         // makes the rdv
  5936.         $rdv = new Rdv();
  5937.         $rdv->setIdAudio($audio);
  5938.         if (isset($proche)) {
  5939.             $rdv->setIdProche($proche);
  5940.         }
  5941.         if (isset($data["client_id_temp"])) {
  5942.             $rdv->setIdClientTemp($client);
  5943.         } else {
  5944.             $rdv->setIdClient($client);
  5945.         }
  5946.         $rdv->setIsMyaudio(true);
  5947.         if (isset($data["isRdvLead"])) {
  5948.             $rdv->setIsRdvLp(true);
  5949.         }
  5950.         if (isset($data["isRdvRapide"])) {
  5951.             $rdv->setIsRdvRapide(true);
  5952.         }
  5953.         if (isset($data["duree"])) {
  5954.             $rdv->setDuration($data["duree"]);
  5955.         }
  5956.         if (isset($data["color"])) {
  5957.             $rdv->setColor($data["color"]);
  5958.         }
  5959.         /** @var Centre */
  5960.         if (isset($data["centre_id"])) {
  5961.             $centre $this->getDoctrine()
  5962.                 ->getRepository(Centre::class)
  5963.                 ->findOneBy(['id' => $data["centre_id"]]);
  5964.             if ($centre == null) {
  5965.                 return new Response(json_encode(([
  5966.                     'message' => 'Error, no centre found at this id',
  5967.                     'path' => 'src/Controller/RdvController.php',
  5968.                     "status" => 400,
  5969.                 ])), 400);
  5970.             }
  5971.             /** @var AudioCentre */
  5972.             $liaison $this->getDoctrine()
  5973.                 ->getRepository(AudioCentre::class)
  5974.                 ->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
  5975.             if ($liaison == null) {
  5976.                 return new Response(json_encode(([
  5977.                     'message' => 'Error, audio isnt part of the centre',
  5978.                     'path' => 'src/Controller/RdvController.php',
  5979.                     "status" => 400,
  5980.                 ])), 400);
  5981.             }
  5982.             $rdv->setIdCentre($centre);
  5983.         } elseif (isset($data["lieu_id"]) && $audio->getIsIndie()) {
  5984.             // tries to set the lieu if it's an audio indie
  5985.             $lieu $this->getDoctrine()
  5986.                 ->getRepository(Lieu::class)
  5987.                 ->findOneBy(['id' => $data["lieu_id"], 'id_gerant' => $data["audio_id"]]);
  5988.             if ($lieu == null) {
  5989.                 return new Response(json_encode(([
  5990.                     'message' => 'Error, no lieu found at this id',
  5991.                     'path' => 'src/Controller/RdvController.php',
  5992.                     "status" => 400,
  5993.                 ])), 400);
  5994.             }
  5995.             $rdv->setIdLieu($lieu);
  5996.         } else {
  5997.             return new Response(json_encode(([
  5998.                 'message' => 'Error, no lieu/centre id',
  5999.                 'path' => 'src/Controller/RdvController.php',
  6000.                 "status" => 400,
  6001.             ])), 400);
  6002.         }
  6003.         /** @var Motif */
  6004.         $motif $this->getDoctrine()
  6005.             ->getRepository(Motif::class)
  6006.             ->find($data["motif_id"]);
  6007.         if ($motif == null) {
  6008.             return new Response(json_encode(([
  6009.                 'message' => 'Error, no motif found at this id',
  6010.                 'path' => 'src/Controller/RdvController.php',
  6011.                 "status" => 400,
  6012.             ])), 400);
  6013.         }
  6014.         /** @var AudioMotif */
  6015.         $audioMotif $this->getDoctrine()
  6016.             ->getRepository(AudioMotif::class)
  6017.             ->findOneBy(["id_audio" => $audio->getId(), "id_motif" => $data["motif_id"]]);
  6018.         if ($audioMotif == null) {
  6019.             return new Response(json_encode(([
  6020.                 'message' => 'Error, no motif of this id found at this audio',
  6021.                 'path' => 'src/Controller/RdvController.php',
  6022.                 "status" => 400,
  6023.             ])), 400);
  6024.         }
  6025.         // remove the taken schedule by rdv to make sure there is no overlap
  6026.         $data["date"] = str_replace("h"":"$data["date"]);
  6027.         $date \DateTime::createFromFormat("Y-m-d\TH:i"$data["date"]);
  6028.         if (isset($data["note"])) {
  6029.             $rdv->setNote($data["note"]);
  6030.         }
  6031.         $date \DateTime::createFromFormat("Y-m-d\TH:i"$data["date"]);
  6032.         $rdv->setDate($date);
  6033.         $rdv->setDateCreation(\DateTime::createFromFormat("d/m/Y H:i"date('d/m/Y H:i')));
  6034.         /** @var EtatRdv */
  6035.         $etat $this->getDoctrine()
  6036.             ->getRepository(EtatRdv::class)
  6037.             ->findOneBy(['id' => $data["etat_id"]]);
  6038.         if ($etat == null) {
  6039.             return new Response(json_encode(([
  6040.                 'message' => 'Error, no etat found at this id',
  6041.                 'path' => 'src/Controller/RdvController.php',
  6042.                 "status" => 400,
  6043.             ])), 400);
  6044.         }
  6045.         $rdv->setIdEtat($etat);
  6046.         $rdv->setIdMotif($motif);
  6047.         $rdv->setIsAbsence(0);
  6048.         $rdv->setCacher(0);
  6049.         $entityManager $this->getDoctrine()->getManager();
  6050.         $entityManager->persist($rdv);
  6051.         $leadRdv->setRdv($rdv);
  6052.         $leadStatus $this->entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'rdv_valider']);
  6053.         $leadRdv->setLeadStatus($leadStatus);
  6054.         $entityManager->flush();
  6055.         /// SMSEMAIL A décommenter pour autoriser l'envoi de sms / email à la création de rdv par l'audio / le client SMSEMAIL ///
  6056.         $date $rdv->getDate();
  6057.         $smsDate $date->format('d-m-Y H:i');
  6058.         $locale 'fr_FR';
  6059.         $formatter = new IntlDateFormatter(
  6060.             $locale,
  6061.             IntlDateFormatter::FULL,
  6062.             IntlDateFormatter::SHORT,
  6063.             null,
  6064.             IntlDateFormatter::GREGORIAN,
  6065.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  6066.         );
  6067.         $smsDateLongFormat $formatter->format($date);
  6068.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  6069.         $client->setIdCentre($rdv->getIdCentre());
  6070.         $client->setIdAudio($rdv->getIdAudio());
  6071.         $entityManager->persist($client);
  6072.         $entityManager->flush();
  6073.         // client notif mail Sms
  6074.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  6075.         $frenchDate ucfirst($frenchDate);
  6076.         $params = array(
  6077.             "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  6078.             "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  6079.             "date" => $smsDateLongFormat,
  6080.             "RdvDate" => $smsDateLongFormat,
  6081.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  6082.             "centerName" => $rdv->getIdCentre()->getName(),
  6083.             "prenom" => $client->getName(),
  6084.             "centerAddress" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  6085.             "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  6086.             'motif' => $rdv->getIdMotif()->getTitre(),
  6087.             "centerCity" => $rdv->getIdCentre()->getCity(),
  6088.             "audioName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  6089.             'titre' => "Votre rendez-vous est validé le " substr($smsDate010) . " à "  substr($smsDate1115),
  6090.             "position" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  6091.             "address" => $rdv->getIdCentre()->getAddress(),
  6092.             "postal" => $rdv->getIdCentre()->getPostale(),
  6093.             "city" => $rdv->getIdCentre()->getCity(),
  6094.             "clientEmail" => $client->getMail(),
  6095.             "clientPassword" => isset($data["passwordGenerated"]) ? $data["passwordGenerated"] : null,
  6096.             "clientAddress" => $client->getAddress(),
  6097.             "clientPostal" => $client->getPostal(),
  6098.             "clientCity" => $client->getCity(),
  6099.             "audioName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  6100.             "frenchDate" => $frenchDate,
  6101.             "heure" => substr($smsDate1115),
  6102.             "centerName" => $rdv->getIdCentre()->getName(),
  6103.             "audioMail" => $rdv->getIdAudio()->getMail(),
  6104.             "modifUrl" => "{$_ENV['BASE_client']}mes-rendez-vous",
  6105.         );
  6106.         $paramsPatient $params;
  6107.         $isNew false;
  6108.         if (isset($data["isLead"]) && isset($data["passwordGenerated"]) != null) {
  6109.             $subject "✅Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  6110.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject189);
  6111.             $isNew true;
  6112.         } else {
  6113.             $subject "Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  6114.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject181);
  6115.         }
  6116.         $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.";
  6117.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  6118.         // audio Notif mail SMS
  6119.         $birthday $rdv->getIdClient()->getBirthdate();
  6120.         $params = array(
  6121.             "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  6122.             "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  6123.             "date" => substr($smsDate010),
  6124.             "heure" => substr($smsDate1115),
  6125.             "mail" => $client->getMail(),
  6126.             "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  6127.             'telClient' => $client->getPhone(),
  6128.             'phone' => $client->getPhone(),
  6129.             'clientCivilite' => $client->getCivilite(),
  6130.             'clientNom' => $client->getLastname(),
  6131.             'clientPrenom' => $client->getName(),
  6132.             'clientPostal' => $client->getPostal(),
  6133.             'clientMail' => $client->getMail(),
  6134.             'clientPhone' => $client->getPhone(),
  6135.             'motif' => $rdv->getIdMotif()->getTitre(),
  6136.             'birthdate' => $client->getBirthdate() ? $client->getBirthdate()->format("d/m/Y") : null,
  6137.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  6138.             'centerName' => $rdv->getIdCentre()->getName(),
  6139.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  6140.             'centerCity' => $rdv->getIdCentre()->getCity(),
  6141.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  6142.             'idPatient' => $client->getId(),
  6143.             'proUrl' => "{$_ENV['BASE_logiciel']}",
  6144.             'frenchDate' => $frenchDate,
  6145.             'responses' => $responses,
  6146.         );
  6147.         $templateEmail 182;
  6148.         if (!empty($data['canMove'])) {
  6149.             $templateEmail 197;
  6150.         }
  6151.         $subject "✅ Nouveau Rendez-vous My Audio le " $frenchDate " à " substr($smsDate1115);
  6152.         // $publicFunction->sendEmail($params, $rdv->getIdAudio()->getMail(), $rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(), $subject, $templateEmail);
  6153.         $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.";
  6154.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$rdv->getIdAudio()->getPhone());
  6155.         $age null;
  6156.         if ($client->getBirthdate()) {
  6157.             $age $client->getBirthdate()->diff(new \DateTime())->y;
  6158.         }
  6159.         // Génère le PDF à partir d’un template
  6160.         $pdfContent $this->generatePdf(
  6161.             'pdf/rdv_recap.html.twig',
  6162.             [
  6163.                 'nom' => $client->getName() ?? '',
  6164.                 'prenom' => $client->getLastname() ?? '',
  6165.                 'birthday' =>  $client->getBirthdate() ? $client->getBirthdate()->format("d/m/Y") : null,
  6166.                 'age' => $age,
  6167.                 'adresse' => $client->getAddress() ?? '',
  6168.                 'postal' => $client->getPostal() ?? '',
  6169.                 'city' => $client->getCity() ?? '',
  6170.                 'phone' => $client->getPhone() ?? '',
  6171.                 'mail' => $client->getMail() ?? '',
  6172.                 'centerName' => $rdv->getIdCentre()->getName() ?? '',
  6173.                 "date" => substr($smsDate010) ?? '',
  6174.                 "heure" => substr($smsDate1115) ?? '',
  6175.                 'duration' => $rdv->getDuration(),
  6176.                 "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  6177.                 'motif' => $rdv->getIdMotif() ? $rdv->getIdMotif()->getTitre() : '',
  6178.                 'situations' => $this->formatImploded($leadRdv->getSituationsGene()),
  6179.                 'IntensiteGen' => $leadRdv->getIntensiteGene() ?? '',
  6180.                 'devicePref' => $this->formatImploded($leadRdv->getPreferenceDevice()),
  6181.                 'deviceModelPref' =>  implode(", "$leadRdv->getDeviceModelPreference()),
  6182.                 'criterePrincipal' => $this->formatImploded($leadRdv->getCriterePrincipal()),
  6183.                 'accoupheneCote' =>  $leadRdv->getAcoupheneCote() ?? '',
  6184.                 'originePerte' => $this->formatImploded($leadRdv->getOriginePerte()),
  6185.                 'diabete' =>  $leadRdv->getDiabete() ?? '',
  6186.                 'hypertension' =>  $leadRdv->getHypertension() ?? '',
  6187.                 'mutuelle' =>  $leadRdv->getMutuelle() ?? '',
  6188.                 'nameMutuelle' =>  $leadRdv->getNameMutuelle() ?? '',
  6189.                 'priseEnCharge' => $leadRdv->getPriseEnCharge() ?? '',
  6190.                 'budget' => $leadRdv->getBudget() ?? '',
  6191.                 'equipeAppareil' => $leadRdv->getEquipeAppareil() ?? '',
  6192.                 'durationEquipe' => $leadRdv->getDurationEquipeAppareil() ?? '',
  6193.                 'bilanAuditif' => $leadRdv->getBilanAuditif() ?? '',
  6194.                 'ordonance' => $leadRdv->getOrdonance() ?? '',
  6195.                 'dateOrdonance' => $leadRdv->getDateOrdonance() ?? '',
  6196.                 'canMove' => $leadRdv->getCanMove() ?? '',
  6197.                 'comment' => $leadRdv->getComment() ?? '',
  6198.             ],
  6199.             $this->getParameter('kernel.project_dir') . '/public/assets/pdf/recap-rdv-myaudio.pdf'
  6200.         );
  6201.         $this->sendEmailWithPdfAttachmentThenDelete(
  6202.             $params,
  6203.             $rdv->getIdAudio()->getMail(),
  6204.             $client->getName(),
  6205.             $subject,
  6206.             $templateEmail// ID du template Sendinblue
  6207.             $pdfContent
  6208.         );
  6209.         // send notif to admin
  6210.         $paramsSourceLead = [
  6211.             'trafficSource' => "EasyAdmin",
  6212.         ];
  6213.         $paramsAdmin = array(
  6214.             "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  6215.             "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  6216.             "RdvDate" => substr($smsDate010),
  6217.             "heure" => substr($smsDate1115),
  6218.             "clientMail" => $client->getMail(),
  6219.             "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  6220.             'telClient' => $client->getPhone(),
  6221.             'clientNom' => $client->getLastname(),
  6222.             'clientPrenom' => $client->getName(),
  6223.             'clientCivilite' => $client->getCivilite(),
  6224.             'clientPostal' => $client->getPostal(),
  6225.             'clientPhone' => $client->getPhone(),
  6226.             'motif' => $rdv->getIdMotif()->getTitre(),
  6227.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  6228.             'centerName' => $rdv->getIdCentre()->getName(),
  6229.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  6230.             'centerCity' => $rdv->getIdCentre()->getCity(),
  6231.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  6232.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  6233.             'date' => substr($smsDate010),
  6234.             'urlApi' => "{$_ENV['BASE_API']}",
  6235.             'clientId' => $client->getId(),
  6236.             'centerId' => $rdv->getIdCentre()->getId(),
  6237.             'frenchDate' => $frenchDate,
  6238.             'responses' => $responses,
  6239.             'paramsSourceLead' => $paramsSourceLead
  6240.         );
  6241.         $subject "Nouveau RDV MA | RR - " $rdv->getIdCentre()->getName();
  6242.         $templateEmail 183;
  6243.         if (!empty($data['canMove'])) {
  6244.             $templateEmail 190;
  6245.         }
  6246.         if (!isset($data["isLead"])) {
  6247.             $publicFunction->sendEmail($paramsAdmin"lead.myaudio@gmail.com""my audio"$subject$templateEmail);
  6248.         }
  6249.         //dd($paramsAdmin);
  6250.         //$publicFunction->sendEmail($paramsAdmin,"testpation1254@yopmail.com","my audio", 'Nouveau RDV à My Audio Pro', $templateEmail);
  6251.         $publicFunction->sendEmail($paramsAdmin"mickael.aubard@myaudio.fr""my audio"$subject$templateEmail);
  6252.         $publicFunction->sendEmail($paramsAdmin"mickael@aubard.me""my audio"$subject$templateEmail);
  6253.         // google calendar post
  6254.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  6255.             ->findBy(array('audio' => $audio->getId()));
  6256.         $data['rdv'] = $rdv->getId();
  6257.         foreach ($synchronisations as $synchronisation) {
  6258.             if (!$synchronisation->getIsDeleted()) {
  6259.                 $googleCalendar->checkAndRefreshAccessToken($synchronisation);
  6260.                 $googleCalendar->createEvent($synchronisation$data);
  6261.             }
  6262.         }
  6263.         return new Response(json_encode(([
  6264.             "id" => $rdv->getId(),
  6265.             "motif_id" => $rdv->getIdMotif()->getId(),
  6266.             "audio_id" => $rdv->getIdAudio()->getId(),
  6267.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  6268.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  6269.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  6270.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  6271.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  6272.             "testclient" => $rdv->getTestClient() ? [
  6273.                 "result" => $rdv->getTestClient()->getResultTonal(),
  6274.                 "date" => $rdv->getTestClient()->getDate(),
  6275.                 "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  6276.             ] : null,
  6277.             "duration" => $audioMotif->getDuration(),
  6278.             "consigne" => $audioMotif->getConsigne(),
  6279.             "etat_id" => $rdv->getIdEtat()->getId(),
  6280.             "date" => $rdv->getDate(),
  6281.             "comment" => $rdv->getComment(),
  6282.             "centerName" => $rdv->getIdCentre()->getName(),
  6283.             "review" => $rdv->getReview(),
  6284.             "note" => $rdv->getNote(),
  6285.             "status" => 200,
  6286.             "paramsPatient" => $paramsPatient,
  6287.             "isNew" => $isNew,
  6288.         ])));
  6289.     }
  6290.     private function generatePdf(string $template, array $data = [], string $outputPath): string
  6291.     {
  6292.         // Render le contenu HTML avec Twig
  6293.         $html $this->twig->render($template$data);
  6294.         // Configurer Dompdf
  6295.         $options = new Options();
  6296.         $options->set('defaultFont''Arial');
  6297.         $dompdf = new Dompdf($options);
  6298.         $dompdf->loadHtml($html);
  6299.         $dompdf->setPaper('A4''portrait');
  6300.         $dompdf->render();
  6301.         // Sauvegarder le PDF
  6302.         file_put_contents($outputPath$dompdf->output());
  6303.         return $outputPath// Renvoie le chemin du fichier PDF généré
  6304.     }
  6305.     private function sendEmailWithPdfAttachmentThenDelete(
  6306.         array $params,
  6307.         string $mail,
  6308.         string $name,
  6309.         string $subject,
  6310.         int $templateId,
  6311.         string $pdfFilePath
  6312.     ): void {
  6313.         // Lire et encoder le contenu du PDF
  6314.         $attachment = [
  6315.             "name" => basename($pdfFilePath),
  6316.             "content" => base64_encode(file_get_contents($pdfFilePath)),
  6317.         ];
  6318.         // Construire les données pour l’API Sendinblue
  6319.         $data = [
  6320.             "sender" => [
  6321.                 "email" => 'noreply@myaudio.fr',
  6322.                 "name" => 'My Audio',
  6323.             ],
  6324.             "to" => [
  6325.                 [
  6326.                     "email" => $mail,
  6327.                     "name" => $name,
  6328.                 ],
  6329.             ],
  6330.             "subject" => $subject,
  6331.             "templateId" => $templateId,
  6332.             "params" => $params,
  6333.             "attachment" => [$attachment],
  6334.         ];
  6335.         // Envoi via cURL
  6336.         $ch curl_init();
  6337.         curl_setopt($chCURLOPT_URL'https://api.sendinblue.com/v3/smtp/email');
  6338.         curl_setopt($chCURLOPT_RETURNTRANSFER1);
  6339.         curl_setopt($chCURLOPT_POST1);
  6340.         curl_setopt($chCURLOPT_POSTFIELDSjson_encode($data));
  6341.         $headers = [
  6342.             'Accept: application/json',
  6343.             'Api-Key: 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',
  6344.             'Content-Type: application/json',
  6345.         ];
  6346.         curl_setopt($chCURLOPT_HTTPHEADER$headers);
  6347.         $result curl_exec($ch);
  6348.         if (curl_errno($ch)) {
  6349.             echo 'Erreur email : ' curl_error($ch);
  6350.         }
  6351.         curl_close($ch);
  6352.         // Supprimer le PDF après envoi
  6353.         if (file_exists($pdfFilePath)) {
  6354.             unlink($pdfFilePath);
  6355.         }
  6356.     }
  6357.     private function formatImploded(array $data): string
  6358.     {
  6359.         return implode(', 'array_map(function ($item) {
  6360.             return str_replace('_'' '$item);
  6361.         }, $data));
  6362.     }
  6363.     /**
  6364.      * 
  6365.      * @Route("/admin/rdv/export-pdf-form", name="admin_rdv_export_pdf_form", methods={"GET", "POST"})
  6366.      */
  6367.     public function exportPdfForm(Request $request): Response
  6368.     {
  6369.         $form $this->createFormBuilder()
  6370.             ->add('startDate'\Symfony\Component\Form\Extension\Core\Type\DateType::class, [
  6371.                 'label' => 'Date de départ',
  6372.                 'widget' => 'single_text',
  6373.                 'html5' => true,
  6374.                 'required' => true,
  6375.             ])
  6376.             ->getForm();
  6377.         $form->handleRequest($request);
  6378.         if ($form->isSubmitted() && $form->isValid()) {
  6379.             $startDate $form->getData()['startDate'];
  6380.             return $this->redirectToRoute('admin_rdv_export_pdf', [
  6381.                 'date' => $startDate->format('Y-m-d'),
  6382.             ]);
  6383.         }
  6384.         return $this->render('easyadmin/rdv/export_pdf_form.html.twig', [
  6385.             'form' => $form->createView(),
  6386.         ]);
  6387.     }
  6388.     /**
  6389.      * 
  6390.      * @Route("/admin/rdv/export-pdf/{date}", name="admin_rdv_export_pdf", methods={"GET", "POST"})
  6391.      */
  6392.     public function exportPdfFromDate(string $date): Response
  6393.     {
  6394.         $startDate = new \DateTimeImmutable($date);
  6395.         $today = new \DateTimeImmutable();
  6396.         $rdvs $this->rdvRepository->findBySinceDateAndMyAudio($startDate);
  6397.         $html "
  6398.         <html>
  6399.         <head>
  6400.             <style>
  6401.                 body {
  6402.                     font-family: Arial, sans-serif;
  6403.                     font-size: 13px; /* Taille de police réduite */
  6404.                 }
  6405.                 table {
  6406.                     width: 100%;
  6407.                     border-collapse: collapse;
  6408.                     font-size: 11px; /* Taille de police spécifique pour le tableau */
  6409.                 }
  6410.                 th, td {
  6411.                     border: 1px solid #000;
  6412.                     padding: 5px;
  6413.                     text-align: left;
  6414.                 }
  6415.                 th {
  6416.                     font-weight: bold;
  6417.                 }
  6418.                 h1 {
  6419.                     font-size: 14px; /* Taille du titre */
  6420.                 }
  6421.             </style>
  6422.         </head>
  6423.         <body>
  6424.             <h1>Rendez-vous My Audio depuis le " $startDate->format('d/m/Y') . "</h1>
  6425.             <table cellspacing='0' cellpadding='5'>
  6426.                 <thead>
  6427.                     <tr>
  6428.                         <th>ID du RDV</th>
  6429.                         <th>Date du RDV</th>
  6430.                         <th>Jours écoulés</th>
  6431.                         <th>Statut RDV</th>
  6432.                         <th>Nom patient</th>
  6433.                         <th>Téléphone patient</th>
  6434.                         <th>Statut patient</th>
  6435.                         <th>Centre</th>
  6436.                         <th>Téléphone Centre</th>
  6437.                         <th>Adresse</th>
  6438.                         <th>Nom Audio</th>
  6439.                     </tr>
  6440.                 </thead>
  6441.                 <tbody>";
  6442.         foreach ($rdvs as $rdv) {
  6443.             $dateRdv $rdv->getDate();
  6444.             $joursEcoules $dateRdv->diff($today)->days;
  6445.             $client $rdv->getIdClient();
  6446.             $centre $rdv->getIdCentre();
  6447.             $etat $rdv->getIdEtat();
  6448.             $clientName $client htmlspecialchars($client->getName() . ' ' $client->getLastname()) : '';
  6449.             $clientPhone $client htmlspecialchars($client->getPhone()) : '';
  6450.             $clientStatus $client && $client->getClientStatus() ? htmlspecialchars($client->getClientStatus()->getLibelle()) : 'Non défini';
  6451.             $rdvStatus $etat htmlspecialchars($etat->getLibelle()) : 'Non défini';
  6452.             $centreName $centre htmlspecialchars($centre->getName()) : '';
  6453.             $centrePhone $centre htmlspecialchars($centre->getPhone()) : '';
  6454.             $centreAddress $centre htmlspecialchars($centre->getAddress() . ', ' $centre->getPostale() . ' ' $centre->getCity()) : '';
  6455.             $audio $rdv->getIdAudio();
  6456.             $audioName $audio htmlspecialchars($audio->getCivilite() . ' ' $audio->getName() . ' ' $audio->getLastname()) : '';
  6457.             $html .= "<tr>
  6458.                  <td>" $rdv->getId() . "</td>
  6459.                 <td>" $dateRdv->format('d/m/Y H:i') . "</td>
  6460.                 <td>" $joursEcoules " jours</td>
  6461.                 <td>" $rdvStatus "</td>
  6462.                 <td>" $clientName "</td>
  6463.                 <td>" $clientPhone "</td>
  6464.                 <td>" $clientStatus "</td>
  6465.                 <td>" $centreName "</td>
  6466.                 <td>" $centrePhone "</td>
  6467.                 <td>" $centreAddress "</td>
  6468.                 <td>" $audioName "</td>
  6469.             </tr>";
  6470.         }
  6471.         $html .= "</tbody></table></body></html>";
  6472.         $options = new Options();
  6473.         $options->set('defaultFont''Arial');
  6474.         $dompdf = new Dompdf($options);
  6475.         $dompdf->loadHtml($html);
  6476.         $dompdf->setPaper('A4''landscape');
  6477.         $dompdf->render();
  6478.         // Création du dossier s’il n’existe pas
  6479.         $outputDir 'public/assets/pdf/rdv';
  6480.         $filesystem = new Filesystem();
  6481.         if (!$filesystem->exists($outputDir)) {
  6482.             $filesystem->mkdir($outputDir0775);
  6483.         }
  6484.         // Formatage du nom du fichier avec la date
  6485.         $filenameDate $startDate->format('Y-m-d');
  6486.         $outputPath "$outputDir/rdvs-since-$filenameDate.pdf";
  6487.         file_put_contents($outputPath$dompdf->output());
  6488.         // Optionnel : téléchargement immédiat du fichier
  6489.         return new Response($dompdf->output(), 200, [
  6490.             'Content-Type' => 'application/pdf',
  6491.             'Content-Disposition' => 'attachment; filename="rdvs-since-' $filenameDate '.pdf"',
  6492.         ]);
  6493.     }
  6494. }