src/Controller/MessageController.php line 314

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  4. use Symfony\Component\HttpFoundation\Response;
  5. use Symfony\Component\Routing\Annotation\Route;
  6. use App\Entity\Message;
  7. use Symfony\Contracts\HttpClient\HttpClientInterface;
  8. use App\Form\MessageType;
  9. use App\Repository\TypeMessageRepository;
  10. use App\Repository\MessageRepository;
  11. use Doctrine\ORM\EntityManagerInterface;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpFoundation\File\Exception\FileException;
  14. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  15. use App\Entity\Client;
  16. use App\Entity\Conversation;
  17. use App\Entity\StatutConversation;
  18. use App\Entity\Canal;
  19. use App\Entity\RechercheAppuisConseil;
  20. use Symfony\Component\HttpFoundation\JsonResponse;
  21. use Lexik\Bundle\JWTAuthenticationBundle\Encoder\JWTEncoderInterface;
  22. use App\Repository\ClientRepository;
  23. use App\Repository\ConversationRepository;
  24. use App\Repository\CanalRepository;
  25. use App\Repository\StatutConversationRepository;
  26. use App\Entity\Session;
  27. use App\Repository\RechercheAgroMeteoRepository;
  28. use App\Repository\RechercheAppuisConseilRepository;
  29. use App\Entity\RechercheAgroMeteo;
  30. use App\Repository\RecherchePrixRepository;
  31. use App\Entity\RecherchePrix;
  32. use App\Repository\SessionRepository;
  33. use App\Fonctions\Fonctions;
  34. use App\Repository\UserRepository;
  35. use DateTimeImmutable;
  36. class MessageController extends AbstractController
  37. {
  38.     private $client;
  39.     public function __construct(SessionInterface $session,HttpClientInterface $client,Fonctions $fonct)
  40.     {
  41.         $this->client $client;
  42.         $this->fonct $fonct;
  43.         $this->session $session;
  44.        
  45.     }
  46.    
  47.     // #[Route('/webhook/garbal/messagerie', methods: ['GET','POST'])]
  48.     // public function messageriewebhook(Request $request): Response
  49.     // {
  50.     //     $verifyToken = "QJEOIDJQEILDJLQDJLEQCLKFDEQLKLEQSKDKQEM";
  51.     //     $mode = trim((string) $request->query->get('hub_mode'));
  52.     //     $token = trim((string) $request->query->get('hub_verify_token'));
  53.     //     $challenge = $request->query->get('hub_challenge');
  54.     //     if ($mode === 'subscribe' && $token === $verifyToken) {
  55.     //         return new Response($challenge, 200, ['Content-Type' => 'text/plain']);
  56.     //     }
  57.     //     return new Response('Forbidden: '.$token, 403);
  58.     // }
  59.     #[Route('/webhook/garbal/messagerie'name'app_webhook_garbal_messagerie'methods: ['GET''POST'])]
  60.     public function messageriewebhook(Request $requestConversationRepository $ConversationRepositoryStatutConversationRepository $StatutConversationRepositoryCanalRepository $CanalRepositoryClientRepository $ClientRepositoryTypeMessageRepository $TypeMessageRepositoryEntityManagerInterface $entityManager,HttpClientInterface $httpClient): Response
  61.     {
  62.         $json $request->getContent();
  63.         $data json_decode($jsontrue);
  64.         if (!$data) {
  65.             return new Response('Invalid JSON'400);
  66.         }
  67.         // Vérifier qu'il y a un message entrant
  68.         if (!isset($data['entry'][0]['changes'][0]['value']['messages'][0])) {
  69.             return new Response('No message'200);
  70.         }
  71.         $value $data['entry'][0]['changes'][0]['value'];
  72.         // Récupérations
  73.         $numero $value['messages'][0]['from'] ?? null;
  74.         $nomPrenom $value['contacts'][0]['profile']['name'] ?? null;
  75.         $typeMessage $value['messages'][0]['type'] ?? null;
  76.         // $body = $value['messages'][0]['text']['body'] ?? null;
  77.         $client $ClientRepository->findOneBy(['telephone' => $numero'statut' => 1]);
  78.         if (!$client) {
  79.             $client = new Client();
  80.             $client->setNomPrenom($nomPrenom);
  81.             $client->setTelephone($numero);
  82.             $client->setAdresse("");
  83.             $client->setCreatedAt(new DateTimeImmutable());
  84.             $client->setStatut(1);
  85.             $entityManager->persist($client);
  86.             $entityManager->flush();
  87.         }
  88.         $conversation $ConversationRepository->findOneBy(['id_client' => $client->getId(), 'id_statut_conversation' => 1]);
  89.         // $this->MessageSimple("ok", $numero);
  90.         if (!$conversation) {
  91.             $conversation = new Conversation();
  92.             // $conversation->setIdUser($name);
  93.             $conversation->setIdClient($client);
  94.             $conversation->setIdStatutConversation($StatutConversationRepository->findOneBy(['id'=>1]));
  95.             // $conversation->setObjet("");
  96.             $conversation->setDateDebutConversation(new DateTimeImmutable());
  97.             // $conversation->setDateFinConversation($number);
  98.             $conversation->setCreatedAt(new DateTimeImmutable());
  99.             $conversation->setStatut(1);
  100.             $entityManager->persist($conversation);
  101.             $entityManager->flush();
  102.         }
  103.         $message = new Message();
  104.         $message->setTelephone($numero);
  105.         $message->setIdCanal($CanalRepository->findOneBy(['id'=>1]));
  106.         $message->setIdConversation($conversation);
  107.         $message->setCreatedAt(new DateTimeImmutable());
  108.         $message->setStatus(1);
  109.         switch ($typeMessage) {
  110.             case 'text':
  111.                 $body $value['messages'][0]['text']['body'] ?? null;
  112.                 $message->setIdTypeMessage($TypeMessageRepository->findOneBy(['id'=>1]));
  113.                 $message->setContenus($body);
  114.                 break;
  115.             case 'image':
  116.                 $imageId $value['messages'][0]['image']['id'] ?? null;
  117.                 $caption $value['messages'][0]['image']['caption'] ?? null;
  118.                 if ($imageId) {
  119.                     $token $_ENV['WHATSAPP_TOKEN'];
  120.                     // récupérer l'URL du média
  121.                     $response $httpClient->request(
  122.                         'GET',
  123.                         "https://graph.facebook.com/v22.0/$imageId",
  124.                         [
  125.                             'headers' => [
  126.                                 'Authorization' => 'Bearer '.$token
  127.                             ]
  128.                         ]
  129.                     );
  130.                     $mediaData $response->toArray();
  131.                     $imageUrl $mediaData['url'];
  132.                     // $imageUrl = 'https://sandbox.crmgarbal.com/uploads/messages/'.$newFilename;
  133.                     
  134.                         // télécharger l'image
  135.                         $imageResponse $httpClient->request(
  136.                             'GET',
  137.                             $imageUrl,
  138.                             [
  139.                                 'headers' => [
  140.                                     'Authorization' => 'Bearer '.$token
  141.                                 ]
  142.                             ]
  143.                         );
  144.                         $imageContent $imageResponse->getContent();
  145.                         $newFilename 'whatsapp_'.uniqid().'.jpg';
  146.                         // $urls = 'https://sandbox.crmgarbal.com/uploads/messages/' . $newFilename;
  147.                         $filePath $this->getParameter('messages_images_directory').'/'.$newFilename;
  148.                         file_put_contents($filePath$imageContent);   
  149.                         
  150.                         $message->addImage($newFilename);
  151.                         $message->setIdTypeMessage($TypeMessageRepository->findOneBy(['id'=>2]));
  152.                         $message->setContenus($caption);
  153.                         $entityManager->persist($message);
  154.                         // $entityManager->flush(); 
  155.                         // $this->MessageSimple("enregistrement effectué", $numero);
  156.                 }
  157.                 break;
  158.             case 'audio':
  159.                 $audioId $value['messages'][0]['audio']['id'] ?? null;
  160.                 $mimeType $value['messages'][0]['audio']['mime_type'] ?? 'audio/ogg';
  161.         // $this->MessageSimple($audioId, $numero);
  162.                 if ($audioId) {
  163.                     $extension str_contains($mimeType'mpeg') ? 'mp3' 'ogg';
  164.                     $audioPath $this->downloadWhatsAppMedia(
  165.                         $audioId,
  166.                         $httpClient,
  167.                         'audio',
  168.                         $extension
  169.                     );
  170.                     $message->setIdTypeMessage($TypeMessageRepository->findOneBy(['id'=>3]));
  171.                     if ($audioPath) {
  172.                         $message->setAudio($audioPath);
  173.                     } else {
  174.                         $message->setContenus("Erreur téléchargement audio");
  175.                     }
  176.                     // $message->setAudio($audioPath);
  177.                 }
  178.                 break;
  179.            case 'video':
  180.                 $videoId $value['messages'][0]['video']['id'] ?? null;
  181.                 $caption $value['messages'][0]['video']['caption'] ?? null;
  182.                 $mimeType $value['messages'][0]['video']['mime_type'] ?? 'video/mp4';
  183.                 if ($videoId) {
  184.                     $extension explode('/'$mimeType)[1] ?? 'mp4';
  185.                     $videoPath $this->downloadWhatsAppMedia(
  186.                         $videoId,
  187.                         $httpClient,
  188.                         'videos',
  189.                         $extension
  190.                     );
  191.                     $message->setVideo($videoPath);
  192.                     $message->setIdTypeMessage($TypeMessageRepository->findOneBy(['id'=>4]));
  193.                     $message->setContenus($caption);
  194.                 }
  195.                 break;
  196.                 case 'document':
  197.                     $documentId $value['messages'][0]['document']['id'] ?? null;
  198.                     $caption $value['messages'][0]['document']['caption'] ?? null;
  199.                     $filename $value['messages'][0]['document']['filename'] ?? null;
  200.                     $mimeType $value['messages'][0]['document']['mime_type'] ?? null;
  201.                     if ($documentId) {
  202.                         $extension pathinfo($filenamePATHINFO_EXTENSION) ?: 'bin';
  203.                         $docPath $this->downloadWhatsAppMedia(
  204.                             $documentId,
  205.                             $httpClient,
  206.                             'documents',
  207.                             $extension
  208.                         );
  209.                         $message->setDocument($docPath);
  210.                         $message->setIdTypeMessage($TypeMessageRepository->findOneBy(['id'=>5]));
  211.                         $message->setContenus($caption ?? $filename);
  212.                     }
  213.                     break;
  214.             case 'location':
  215.                 $latitude  $value['messages'][0]['location']['latitude'] ?? null;
  216.                 $longitude $value['messages'][0]['location']['longitude'] ?? null;
  217.                 $name      $value['messages'][0]['location']['name'] ?? null;
  218.                 $address   $value['messages'][0]['location']['address'] ?? null;
  219.                 if ($latitude && $longitude) {
  220.                     $contenu "Localisation reçue :\n";
  221.                     $contenu .= "Latitude : $latitude\n";
  222.                     $contenu .= "Longitude : $longitude\n";
  223.                     if ($name) {
  224.                         $contenu .= "Nom : $name\n";
  225.                     }
  226.                     if ($address) {
  227.                         $contenu .= "Adresse : $address\n";
  228.                     }
  229.                     $contenu .= "Lien Google Maps : https://www.google.com/maps?q=$latitude,$longitude";
  230.                     $message->setLatitude($latitude);
  231.                     $message->setIdTypeMessage($TypeMessageRepository->findOneBy(['id'=>6]));
  232.                     $message->setLongitude($longitude);
  233.                     $message->setContenus("Localisation envoyée par le client");
  234.                 }else {
  235.                     $this->MessageSimple("Echec"$numero);
  236.                 }
  237.                 break;
  238.         case 'sticker':
  239.             $stickerId  $value['messages'][0]['sticker']['id'] ?? null;
  240.             $mimeType   $value['messages'][0]['sticker']['mime_type'] ?? 'image/webp';
  241.             if ($stickerId) {
  242.                 $extension explode('/'$mimeType)[1] ?? 'webp';
  243.                 $stickerPath $this->downloadWhatsAppMedia(
  244.                     $stickerId,
  245.                     $httpClient,
  246.                     'stickers',
  247.                     $extension
  248.                 );
  249.                 $message->addImage($stickerPath);
  250.                 $message->setIdTypeMessage($TypeMessageRepository->findOneBy(['id'=>7]));
  251.                 $message->setContenus("Sticker envoyé");
  252.             }
  253.             break;
  254.             default:
  255.                 $message->setContenus("Type de message non supporté : ".$typeMessage);
  256.                 break;
  257.         }
  258.         
  259.         $entityManager->persist($message);
  260.         $entityManager->flush();
  261.         $this->MessageSimple("enregistrement effectué"$numero);
  262.         return new Response('EVENT_RECEIVED'200);
  263.         
  264.     }
  265.     //fonction fin convertion
  266.     #[Route('/fin/garbal/conversation'name'app_fin_garbal_conversation')]
  267.     public function FinConversation(Request $requestConversationRepository $ConversationRepositoryStatutConversationRepository $StatutConversationRepositoryEntityManagerInterface $entityManagerHttpClientInterface $httpClient): Response
  268.     {
  269.             
  270.         if ($request->request->count()>0){
  271.             $objet=$request->request->get('objet');
  272.             $commentaire=$request->request->get('commentaire');
  273.             $id=$request->request->get('id');
  274.             $conversation=$ConversationRepository->findOneBy(['id'=>$id]);
  275.             if (!$conversation) {
  276.                 return $this->redirectToRoute('app_whatsapp_communication', [], Response::HTTP_SEE_OTHER);
  277.             }
  278.             
  279.             if ($objet==1) {
  280.                 $conversation->setObjet("AGRO METEO");
  281.             }elseif ($objet==2) {
  282.                 $conversation->setObjet("APPUIS CONSEIL");
  283.             }elseif ($objet==3) {
  284.                 $conversation->setObjet("PRIX");
  285.             }else {
  286.                 $conversation->setObjet("AUTRE");
  287.             }
  288.             $conversation->setCommentaire($commentaire);
  289.             $conversation->setDateFinConversation(new DateTimeImmutable());
  290.             $conversation->setIdStatutConversation($StatutConversationRepository->findOneBy(['id'=>3]));
  291.             $entityManager->persist($conversation);
  292.             
  293.             $entityManager->flush();
  294.         }
  295.         return $this->redirectToRoute('app_whatsapp_communication', [], Response::HTTP_SEE_OTHER);
  296.         
  297.     }
  298.     private function downloadWhatsAppMedia($mediaIdHttpClientInterface $httpClient$folder 'media'$extension 'bin')
  299. {
  300.     $token $_ENV['WHATSAPP_TOKEN'];
  301.     try {
  302.         // 1. Metadata
  303.         $response $httpClient->request(
  304.             'GET',
  305.             "https://graph.facebook.com/v22.0/$mediaId",
  306.             [
  307.                 'headers' => [
  308.                     'Authorization' => 'Bearer '.$token
  309.                 ]
  310.             ]
  311.         );
  312.         $mediaData json_decode($response->getContent(false), true);
  313.         if (!$mediaData || !isset($mediaData['url'])) {
  314.             throw new \Exception('Erreur metadata: '.json_encode($mediaData));
  315.         }
  316.         $mediaUrl $mediaData['url'];
  317.         // 2. Télécharger
  318.         $mediaResponse $httpClient->request(
  319.             'GET',
  320.             $mediaUrl,
  321.             [
  322.                 'headers' => [
  323.                     'Authorization' => 'Bearer '.$token
  324.                 ]
  325.             ]
  326.         );
  327.         $content $mediaResponse->getContent();
  328.         // 3. Dossier
  329.         $basePath $this->getParameter('messages_images_directory');
  330.         $folderPath $basePath '/' $folder;
  331.         if (!is_dir($folderPath)) {
  332.             mkdir($folderPath0777true);
  333.         }
  334.         // 4. Nom fichier
  335.         $newFilename $folder.'_'.uniqid().'.'.$extension;
  336.         $filePath $folderPath '/' $newFilename;
  337.         file_put_contents($filePath$content);
  338.         return $folder '/' $newFilename;
  339.     } catch (\Exception $e) {
  340.         file_put_contents(
  341.             $this->getParameter('kernel.project_dir').'/var/log/whatsapp_error.log',
  342.             date('Y-m-d H:i:s').' - '.$e->getMessage().' - MEDIA ID: '.$mediaId.PHP_EOL,
  343.             FILE_APPEND
  344.         );
  345.         return null;
  346.     }
  347. }
  348.     // private function downloadWhatsAppMedia($mediaId, HttpClientInterface $httpClient, $folder = 'media', $extension = 'bin')
  349.     // {
  350.     //     $token = $_ENV['WHATSAPP_TOKEN'];
  351.     //     try {
  352.     //         // 1. Récupérer les infos du média
  353.     //         $response = $httpClient->request(
  354.     //             'GET',
  355.     //             "https://graph.facebook.com/v22.0/$mediaId",
  356.     //             [
  357.     //                 'headers' => [
  358.     //                     'Authorization' => 'Bearer '.$token
  359.     //                 ]
  360.     //             ]
  361.     //         );
  362.     //         if ($response->getStatusCode() !== 200) {
  363.     //             throw new \Exception('Erreur récupération metadata média');
  364.     //         }
  365.     //         // $mediaData = $response->toArray(false);
  366.     //         // if (!isset($mediaData['url'])) {
  367.     //         //     throw new \Exception('URL média introuvable');
  368.     //         // }
  369.     //         $mediaData = json_decode($response->getContent(false), true);
  370.     //         if (!$mediaData || !isset($mediaData['url'])) {
  371.     //             throw new \Exception('Réponse API invalide : ' . json_encode($mediaData));
  372.     //         }
  373.     //         $mediaUrl = $mediaData['url'];
  374.     //         // 2. Télécharger le fichier
  375.     //         $mediaResponse = $httpClient->request(
  376.     //             'GET',
  377.     //             $mediaUrl,
  378.     //             [
  379.     //                 'headers' => [
  380.     //                     'Authorization' => 'Bearer '.$token
  381.     //                 ]
  382.     //             ]
  383.     //         );
  384.     //         if ($mediaResponse->getStatusCode() !== 200) {
  385.     //             throw new \Exception('Erreur téléchargement média');
  386.     //         }
  387.     //         $content = $mediaResponse->getContent();
  388.     //         // 3. Sécuriser extension
  389.     //         if (!$extension) {
  390.     //             $extension = 'bin';
  391.     //         }
  392.     //         // 4. Créer dossier si inexistant
  393.     //         $basePath = $this->getParameter('messages_directory');
  394.     //         $folderPath = $basePath . '/' . $folder;
  395.     //         if (!is_dir($folderPath)) {
  396.     //             mkdir($folderPath, 0777, true);
  397.     //         }
  398.     //         // 5. Générer nom fichier
  399.     //         $newFilename = $folder.'_'.uniqid().'.'.$extension;
  400.     //         $filePath = $folderPath . '/' . $newFilename;
  401.     //         // 6. Sauvegarde
  402.     //         file_put_contents($filePath, $content);
  403.     //         return $folder . '/' . $newFilename;
  404.     //     } catch (\Exception $e) {
  405.     //         // 🔥 LOG IMPORTANT
  406.     //         file_put_contents(
  407.     //             $this->getParameter('kernel.project_dir').'/var/log/whatsapp_error.log',
  408.     //             date('Y-m-d H:i:s').' - '.$e->getMessage().PHP_EOL,
  409.     //             FILE_APPEND
  410.     //         );
  411.     //         return null;
  412.     //     }
  413.     // }
  414.     private function downloadWhatsAppVideo(string $mediaIdHttpClientInterface $httpClientstring $folderstring $extension ): ?string
  415.     {
  416.         $token $_ENV['EAAesTlijMGcBQtdhdKedpB4DqNDFsDVcuBb8Kcx3zETgu8pMjX67hpliaoL2wAHjgZAJZAo0rPblwFesxiJXqm19ZC5mjQdixA5oYqjpoVYnbq97dqOMnNR8qoT2QqIcaraJDLHdZBd52UTEcxj8qTRT82iqy0GyOltkXdZBtBgrKUc3f1TpHRXHQOZBw3gt7kewZDZD'];
  417.         //  Récupérer l'URL temporaire
  418.         $response $httpClient->request(
  419.             'GET',
  420.             "https://graph.facebook.com/v22.0/$mediaId",
  421.             [
  422.                 'headers' => [
  423.                     'Authorization' => 'Bearer ' $token
  424.                 ]
  425.             ]
  426.         );
  427.         if ($response->getStatusCode() !== 200) {
  428.             return null;
  429.         }
  430.         $mediaData $response->toArray();
  431.         $mediaUrl $mediaData['url'];
  432.         // 2️⃣ Télécharger le fichier
  433.         $mediaResponse $httpClient->request(
  434.             'GET',
  435.             $mediaUrl,
  436.             [
  437.                 'headers' => [
  438.                     'Authorization' => 'Bearer ' $token
  439.                 ]
  440.             ]
  441.         );
  442.         if ($mediaResponse->getStatusCode() !== 200) {
  443.             return null;
  444.         }
  445.         $content $mediaResponse->getContent();
  446.         // 3️⃣ Créer dossier si inexistant
  447.         $uploadDir $this->getParameter('kernel.project_dir') . '/public/uploads/' $folder;
  448.         if (!is_dir($uploadDir)) {
  449.             mkdir($uploadDir0777true);
  450.         }
  451.         $fileName uniqid() . '.' $extension;
  452.         $filePath $uploadDir '/' $fileName;
  453.         file_put_contents($filePath$content);
  454.         
  455.         file_put_contents($filePath$audioContent);
  456.         return '/uploads/video/' $folder '/' $fileName;
  457.     }
  458.     private function downloadWhatsAppDocumentstring $mediaIdHttpClientInterface $httpClientstring $originalFilename null ): ?string
  459.     {
  460.         $token $_ENV['EAAesTlijMGcBQtdhdKedpB4DqNDFsDVcuBb8Kcx3zETgu8pMjX67hpliaoL2wAHjgZAJZAo0rPblwFesxiJXqm19ZC5mjQdixA5oYqjpoVYnbq97dqOMnNR8qoT2QqIcaraJDLHdZBd52UTEcxj8qTRT82iqy0GyOltkXdZBtBgrKUc3f1TpHRXHQOZBw3gt7kewZDZD'];
  461.         // 1️⃣ Récupérer l’URL temporaire via Graph API v22.0
  462.         $response $httpClient->request(
  463.             'GET',
  464.             "https://graph.facebook.com/v22.0/$mediaId",
  465.             [
  466.                 'headers' => [
  467.                     'Authorization' => 'Bearer ' $token
  468.                 ]
  469.             ]
  470.         );
  471.         if ($response->getStatusCode() !== 200) {
  472.             return null;
  473.         }
  474.         $mediaData $response->toArray();
  475.         $mediaUrl $mediaData['url'] ?? null;
  476.         if (!$mediaUrl) {
  477.             return null;
  478.         }
  479.         // 2️⃣ Télécharger le fichier réel
  480.         $fileResponse $httpClient->request(
  481.             'GET',
  482.             $mediaUrl,
  483.             [
  484.                 'headers' => [
  485.                     'Authorization' => 'Bearer ' $token
  486.                 ]
  487.             ]
  488.         );
  489.         if ($fileResponse->getStatusCode() !== 200) {
  490.             return null;
  491.         }
  492.         $content $fileResponse->getContent();
  493.         // 3️⃣ Déterminer l’extension
  494.         $extension pathinfo($originalFilenamePATHINFO_EXTENSION);
  495.         if (!$extension) {
  496.             $extension 'bin';
  497.         }
  498.         // 4️⃣ Créer dossier si inexistant
  499.         $uploadDir $this->getParameter('kernel.project_dir') . '/public/uploads/documents';
  500.         if (!is_dir($uploadDir)) {
  501.             mkdir($uploadDir0777true);
  502.         }
  503.         // 5️⃣ Générer nom unique
  504.         $fileName uniqid() . '.' $extension;
  505.         $filePath $uploadDir '/' $fileName;
  506.         file_put_contents($filePath$content);
  507.         return '/uploads/documents/' $fileName;
  508.     }
  509.      public function MessageSimple(string $contenusstring $numero)
  510.     {
  511.         $numero ltrim($numero'+');
  512.         $apiUrl 'https://graph.facebook.com/v22.0/1037760686078257/messages';
  513.         $token 'EAAesTlijMGcBQtdhdKedpB4DqNDFsDVcuBb8Kcx3zETgu8pMjX67hpliaoL2wAHjgZAJZAo0rPblwFesxiJXqm19ZC5mjQdixA5oYqjpoVYnbq97dqOMnNR8qoT2QqIcaraJDLHdZBd52UTEcxj8qTRT82iqy0GyOltkXdZBtBgrKUc3f1TpHRXHQOZBw3gt7kewZDZD';
  514.         $data = [
  515.             "messaging_product" => "whatsapp",   
  516.             // "recipient_type": "individual",
  517.             "to" => $numero,
  518.             "type" => "text",
  519.             "text" => [
  520.                 "preview_url" => false,
  521.                 "body" => $contenus
  522.             ]
  523.         ];
  524.         $ch curl_init();
  525.         curl_setopt_array($ch, [
  526.             CURLOPT_URL => $apiUrl,
  527.             CURLOPT_RETURNTRANSFER => true,
  528.             CURLOPT_POST => true,
  529.             CURLOPT_TIMEOUT => 10,
  530.       CURLOPT_CUSTOMREQUEST => 'POST',
  531.             CURLOPT_HTTPHEADER => [
  532.                 "Authorization: Bearer $token",
  533.                 "Content-Type: application/json"
  534.             ],
  535.             CURLOPT_POSTFIELDS => json_encode($data)
  536.         ]);
  537.         $response curl_exec($ch);
  538.         $httpCode curl_getinfo($chCURLINFO_HTTP_CODE);
  539.         if (curl_errno($ch)) {
  540.             dump("Curl error: " curl_error($ch));
  541.         }
  542.         curl_close($ch);
  543.         dump("HTTP CODE: " $httpCode);
  544.         dump("RESPONSE: " $response);
  545.         return $response;
  546.     }
  547.     #[Route('/message/communication'name'app_message_communication'methods: ['GET''POST'])]
  548.     public function MessageCommunication(Request $request,SessionRepository $SessionRepository,ClientRepository $ClientRepository,EntityManagerInterface $entityManager): Response 
  549.     {
  550.    
  551.         // $json = $request->getContent();
  552.         // $data = json_decode($json, true);
  553.         // if (!$data || !isset($data['entry'][0]['changes'][0]['value']['messages'][0])) {
  554.         //     return new Response("No message", 200);
  555.         // }
  556.         // $messages = $data['entry'][0]['changes'][0]['value']['messages'][0];
  557.         // $name = $data['entry'][0]['changes'][0]['value']['contacts'][0]['profile']['name'];
  558.         // $number = $messages['from'];
  559.         // $typeMessage = $messages['type'];
  560.         // $body = "";
  561.         // if (isset($messages['text']['body'])) {
  562.         //     $body = trim($messages['text']['body']);
  563.         // }
  564.         // $client = $ClientRepository->findOneBy(['telephone' => $number, 'statut' => 1]);
  565.         // if (!$client) {
  566.         //     $client = new Client();
  567.         //     $client->setNomPrenom($name);
  568.         //     $client->setTelephone($number);
  569.         //     $client->setAdresse("");
  570.         //     $client->setCreatedAt(new DateTimeImmutable());
  571.         //     $client->setStatut(1);
  572.         //     $entityManager->persist($client);
  573.         //     $entityManager->flush();
  574.         // }
  575.         // $session = $SessionRepository->findOneBy(['idClient' => $client->getId(), 'statut' => 1]);
  576.         // if ($body === "Merci" || $body === "Au revoir") {
  577.         //     if ($session) {
  578.         //         $session->setStatut(0);
  579.         //         $session->setDeletedAt(new DateTimeImmutable());
  580.         //         $entityManager->flush();
  581.         //     }
  582.         //     $this->envoyerSimpleMessage(
  583.         //         "*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ très bientôt !",
  584.         //         $number
  585.         //     );
  586.         //     return new Response("", 200);
  587.         // }
  588.         // if (!$session) {
  589.         //     // Ignorer tout ce qui n'est pas un texte
  590.         //     if ($typeMessage !== "text") {
  591.         //         return new Response("", 200);
  592.         //     }
  593.         //     $body = trim($messages['text']['body']);
  594.         //     // Ne pas recréer une session si l'utilisateur dit encore un mot de fin
  595.         //     if ($body === "Merci" || $body === "Au revoir") {
  596.         //         return new Response("", 200);
  597.         //     }
  598.         //     $session = new Session();
  599.         //     $session->setIdClient($client);
  600.         //     $session->setEtape(0);
  601.         //     $session->setTempsConnexion(0);
  602.         //     $session->setCreatedAt(new DateTimeImmutable());
  603.         //     $session->setStatut(1);
  604.         //     $entityManager->persist($session);
  605.         //     $entityManager->flush();
  606.         //     $text = "Bonjour bienvenue *{$name}*\nje suis votre assistante de service *GARBAL*, c'est un plaisir de vous accueillir parmi nous. Je suis là pour vous accompagner à chaque étape.";
  607.         //     $this->MessageChoixService($text, $number);
  608.         //     return new Response("", 200);
  609.         // }
  610.         // if ($session->getEtape() == 0) {
  611.         //     if ($typeMessage == 'interactive') {
  612.         //         $choix = $messages['interactive']['list_reply']['id'];
  613.         //         $session->setService($choix);
  614.         //         $session->setEtape(1);
  615.         //         $entityManager->flush();
  616.         //         switch ($choix) {
  617.         //             case "Sc_001":
  618.         //                 $agrometeo = new RechercheAgroMeteo();
  619.         //                 $agrometeo->setIdSession($session);
  620.         //                 $agrometeo->setEtape(0);
  621.         //                 $agrometeo->setCreatedAt(new DateTimeImmutable());
  622.         //                 $agrometeo->setStatut(1);
  623.         //                 $entityManager->persist($agrometeo);
  624.         //                 $entityManager->flush();
  625.         //                 $this->ChoixInformation("Veuillez choisir le type d'information souhaité.", $number);
  626.         //                 break;
  627.         //             case "Sc_002":
  628.         //                 $app = new RechercheAppuisConseil();
  629.         //                 $app->setIdSession($session);
  630.         //                 $app->setEtape(0);
  631.         //                 $app->setCreatedAt(new DateTimeImmutable());
  632.         //                 $app->setStatut(1);
  633.         //                 $entityManager->persist($app);
  634.         //                 $entityManager->flush();
  635.         //                 $this->ChoixDomaine($number);
  636.         //                 break;
  637.         //             case "Sc_003":
  638.         //                 $prix = new RecherchePrix();
  639.         //                 $prix->setIdSession($session);
  640.         //                 $prix->setEtape(0);
  641.         //                 $prix->setCreatedAt(new DateTimeImmutable());
  642.         //                 $prix->setStatut(1);
  643.         //                 $entityManager->persist($prix);
  644.         //                 $entityManager->flush();
  645.         //                 $this->EnvoyerListeCategories("Veuillez choisir le type d'information souhaité.", $number);
  646.         //                 break;
  647.         //             default:
  648.         //                 $this->envoyerSimpleMessage("Désolé, choix inconnu.", $number);
  649.         //         }
  650.         //         return new Response("", 200);
  651.         //     }
  652.         //     // Pas interactif
  653.         //     $this->envoyerSimpleMessage("Veuillez faire un choix.", $number);
  654.         //     return new Response("", 200);
  655.         // }
  656.         // switch ($session->getService()) {
  657.         //     case "Sc_001":
  658.         //         $this->TraiterAgroMeteo($data, $session, $entityManager);
  659.         //         break;
  660.         //     case "Sc_002":
  661.         //         $this->TraiterAppuisConseil($data, $session, $entityManager);
  662.         //         break;
  663.         //     case "Sc_003":
  664.         //         $this->TraiterPrix($data, $session, $entityManager);
  665.         //         break;
  666.         //     default:
  667.         //         $this->envoyerSimpleMessage("Choix non reconnu.", $number);
  668.         // }
  669.         // return new Response("", 200);
  670.     }
  671.     public function TraiterPrix($data$session$entityManager)
  672.     {
  673.         $messages $data['entry'][0]['changes'][0]['value']['messages'][0];
  674.         $number $messages['from'];
  675.         $typeMessage $messages['type'];
  676.         if ($typeMessage === "text") {
  677.             $texte trim($messages['text']['body']);
  678.             if ($texte === "Merci" || $texte === "Au revoir") {
  679.                 $session->setStatut(0);
  680.                 $session->setDeletedAt(new DateTimeImmutable());
  681.                 $entityManager->persist($session);
  682.                 $entityManager->flush();
  683.                 $this->envoyerSimpleMessage(
  684.                     "*Session expirée*\nMerci d'avoir utilisé notre service prix.\nÀ très bientôt.",
  685.                     $number
  686.                 );
  687.                 return;
  688.             }
  689.         }
  690.         $prixSession $entityManager->getRepository(RecherchePrix::class)
  691.             ->findOneBy(['idSession' => $session->getId(), 'statut' => 1]);
  692.         if (!$prixSession) {
  693.             $this->envoyerSimpleMessage("Aucune session."$number);
  694.                 return;
  695.         }
  696.         /*  ÉTAPE 0 : CHOIX CATÉGORIE  */
  697.         if ($prixSession->getEtape() == 0) {
  698.             if (isset($messages['interactive']['list_reply']['id'])) {
  699.                 $choix $messages['interactive']['list_reply']['id'];
  700.                 if ($choix === "Pc_001") {
  701.                     $prixSession->setType("AGRICULTURE");
  702.                     $prixSession->setEtape(1);
  703.                     $entityManager->flush();
  704.                     $this->envoyerSimpleMessage(
  705.                         "Vous avez choisi *AGRO ALIMENTAIRE*.\n\nVeuillez saisir le nom d'une commune :",
  706.                         $number
  707.                     );
  708.                     return;
  709.                 }
  710.                 if ($choix === "Pc_002") {
  711.                     $prixSession->setType("BETAIL");
  712.                     $prixSession->setEtape(1);
  713.                     $entityManager->flush();
  714.                     $this->envoyerSimpleMessage(
  715.                         "Vous avez choisi *ANIMAUX / BÉTAIL*.\n\nVeuillez saisir le nom d'une commune :",
  716.                         $number
  717.                     );
  718.                     return;
  719.                 }
  720.                 $this->envoyerSimpleMessage("Choix invalide, veuillez réessayer."$number);
  721.                 return;
  722.             }
  723.             // Si aucun choix reçu, envoyer la liste de catégories
  724.             $this->EnvoyerListeCategories("Veuillez choisir une catégorie :"$number);
  725.             return;
  726.         }
  727.         /* ÉTAPE 1 : RECHERCHE DE COMMUNE */
  728.         if ($prixSession->getEtape() == ) {
  729.             if ($typeMessage !== "text") {
  730.                 $this->envoyerSimpleMessage(
  731.                     "Veuillez saisir un nom de commune sous forme de texte.",
  732.                     $number
  733.                 );
  734.                 return;
  735.             }
  736.             $texteRecu trim($messages['text']['body']);
  737.             $listeCommunes $this->AppelApiRechercheCommunes($texteRecu);
  738.             if (empty($listeCommunes)) {
  739.                 $this->envoyerSimpleMessage(
  740.                     "Aucune commune trouvée pour *$texteRecu*.\nVeuillez saisir un autre nom.",
  741.                     $number
  742.                 );
  743.                 return;
  744.             }
  745.             // Stocker la liste pour sélection
  746.             $prixSession->setListeResultat(json_encode($listeCommunes));
  747.             $prixSession->setEtape(2);
  748.             $entityManager->flush();
  749.             $this->EnvoyerListeCommunes($listeCommunes$number);
  750.             return;
  751.         }
  752.         /*  ÉTAPE 2 : CHOIX D'UNE COMMUNE */
  753.         if ($prixSession->getEtape() == && $typeMessage === "text") {
  754.             $choix trim($messages['text']['body']);
  755.             if (!ctype_digit($choix)) {
  756.                 $this->envoyerSimpleMessage("Veuillez saisir un numéro valide."$number);
  757.                 return;
  758.             }
  759.             $listeCommunes json_decode($prixSession->getListeResultat(), true);
  760.             $index intval($choix) - 1;
  761.             if (!isset($listeCommunes[$index])) {
  762.                 $this->envoyerSimpleMessage("Numéro invalide. Veuillez réessayer."$number);
  763.                 return;
  764.             }
  765.             $commune $listeCommunes[$index];
  766.             $prixSession->setCommune($commune['id']);
  767.             $prixSession->setListeResultat(null);
  768.             $prixSession->setEtape(3);
  769.             $entityManager->flush();
  770.             /* les prix selon la catégorie */
  771.             if ($prixSession->getType() === "AGRICULTURE") {
  772.                 $listePrix $this->AppelApiPrixProduitsAgricoles($commune['id']);
  773.                 $this->EnvoyerPrixProduitsAgricoles($listePrix$number);
  774.                 $prixSession->setStatut(0);
  775.                 $prixSession->setDeletedAt(new DateTimeImmutable());
  776.                 $session->setStatut(0);
  777.                 $session->setDeletedAt(new DateTimeImmutable());
  778.                 $entityManager->persist($session);
  779.                 $entityManager->flush();
  780.                 $this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !"$number);
  781.                 return;
  782.             }
  783.             if ($prixSession->getType() === "BETAIL") {
  784.                 $listePrix $this->AppelApiPrixBetail($commune['id']);
  785.                 $this->EnvoyerPrixBetail($listePrix$number);
  786.                 $prixSession->setStatut(0);
  787.                 $prixSession->setDeletedAt(new DateTimeImmutable());
  788.                 $session->setStatut(0);
  789.                 $session->setDeletedAt(new DateTimeImmutable());
  790.                 $entityManager->persist($session);
  791.                 $entityManager->flush();
  792.                 $this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !"$number);
  793.                 return;
  794.             }
  795.             return;
  796.         }
  797.         /* ERREUR PAR DÉFAUT  */
  798.         $this->envoyerSimpleMessage("Désolé, je n'ai pas reconnu votre choix."$number);
  799.         return;
  800.     }
  801.     
  802.     public function EnvoyerListeCommunes(array $listeCommunesstring $number)
  803.     {
  804.         if (empty($listeCommunes)) {
  805.             $this->envoyerSimpleMessage("Aucune commune trouvée. Veuillez réessayer."$number);
  806.             return;
  807.         }
  808.         $message "*Communes trouvées :*\n\n";
  809.         $i 1;
  810.         foreach ($listeCommunes as $commune) {
  811.             $message .= "👉 Tapez *".$i."* pour *".$commune['libelle']."*\n";
  812.             $i++;
  813.         }
  814.         $message .= "\n*Tapez le numéro* correspondant à votre commune.";
  815.         // CORRECTION : utiliser $number et NON $numero
  816.         $this->envoyerSimpleMessage($message$number);
  817.     }
  818.     public function AppelApiRechercheCommunes(string $texte): array 
  819.     {  
  820.         //Authentification API 
  821.         $auth $this->fonct->execPost('''api/authentification'json_encode([
  822.             "email" => "djafarasakinatou@gmail.com",
  823.             "password" => "l2323"
  824.         ]));
  825.           
  826.         //Appel API de recherche des communes 
  827.         $response $this->fonct->execPost$auth['data']['token'], 'api/communes/recherche'json_encode([ "commune" => $texte ]) );  
  828.        
  829.         //Vérification réponse 
  830.         if (!isset($response['status']) || $response['status'] != 200
  831.         { 
  832.             return []; 
  833.         }  
  834.         //Retourne la liste des résultats 
  835.         return $response['results'] ?? []; 
  836.     }
  837.     public function AppelApiPrixBetail(string $idCommune): array 
  838.     { 
  839.         // Authentification API 
  840.         $auth $this->fonct->execPost('''api/authentification'json_encode([
  841.             "email" => "djafarasakinatou@gmail.com",
  842.             "password" => "l2323"
  843.         ]));
  844.         // Appel API Prix Bétail 
  845.         $response $this->fonct->execPost$auth['data']['token'], 'api/prix/animaux'json_encode([ "id_commune" => $idCommune ]) ); 
  846.         if (!isset($response['status']) || $response['status'] != 200
  847.         { 
  848.             return []; 
  849.         } 
  850.         return $response['data'] ?? []; 
  851.     }
  852.     public function AppelApiPrixProduitsAgricoles(string $idCommune): array
  853.     {
  854.         // Authentification API
  855.         $auth $this->fonct->execPost('''api/authentification'json_encode([
  856.             "email" => "djafarasakinatou@gmail.com",
  857.             "password" => "l2323"
  858.         ]));
  859.         // Appel API Prix Produits Agricoles
  860.         $response $this->fonct->execPost(
  861.             $auth['data']['token'],
  862.             'api/prix/produit/agricole',
  863.             json_encode([
  864.                 "id_commune" => $idCommune,
  865.                 "id_semaine" => "" // ton API prend automatiquement la semaine active
  866.             ])
  867.         );
  868.         // Vérification du status
  869.         if (!isset($response['status']) || $response['status'] != 200) {
  870.             return [];
  871.         }
  872.         // Retour des données
  873.         return $response['data'] ?? [];
  874.     }
  875.     public function EnvoyerListeCategories(string $textstring $number
  876.     { 
  877.         $apiUrl 'https://graph.facebook.com/v22.0/870067449513702/messages';
  878.         $token 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
  879.         
  880.         $payload = [ 
  881.             "messaging_product" => "whatsapp"
  882.             "to" => $number
  883.             "type" => "interactive"
  884.             "interactive" => [ 
  885.                 "type" => "list",
  886.                 "body" => [ 
  887.                     "text" => $text 
  888.                 ], 
  889.                 "footer" => [ 
  890.                     "text" => "Pour arrêter le processus tapez merci ou au revoir" 
  891.                 ], 
  892.                 "action" => [ 
  893.                     "button" => "Catégories"
  894.                     "sections" => [ 
  895.                         [ 
  896.                             "title" => "Catégories disponibles"
  897.                             "rows" => [ 
  898.                                 [ 
  899.                                     "id" => "Pc_001"
  900.                                     "title" => "AGRO ALIMENT"
  901.                                     "description" => "Prix des aliments d'une localité du Niger" 
  902.                                 ],
  903.                                 [ 
  904.                                     "id" => "Pc_002"
  905.                                     "title" => "ANIMAUX"
  906.                                     "description" => "Prix du bétail d'une localité du Niger" 
  907.                                 
  908.                             ] 
  909.                         ] 
  910.                     ] 
  911.                 ] 
  912.             ] 
  913.         ]; 
  914.         try { 
  915.             $response $this->client->request('POST'$apiUrl, [ 
  916.                 'headers' => [ 
  917.                     'Authorization' => 'Bearer ' $token
  918.                     'Content-Type' => 'application/json'
  919.                 ], 
  920.                 'json' => $payload
  921.             ]); 
  922.             $result $response->toArray(false); 
  923.             return $result;
  924.         } catch (\Exception $e) {
  925.             return ['error' => $e->getMessage()];
  926.         }
  927.     }
  928.     public function EnvoyerPrixBetail(array $prixstring $number)
  929.     {
  930.         $apiUrl 'https://graph.facebook.com/v22.0/870067449513702/messages';
  931.         $token 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
  932.         // Construction du message
  933.         if (empty($prix)) {
  934.             $texte " *Aucun prix de bétail trouvé pour cette commune.*";
  935.         } else {
  936.             $texte " *Prix du Bétail*\n\n";
  937.             foreach ($prix as $item) {
  938.                 $texte .= " *" $item["animal"] . "*\n";
  939.                 $texte .= " Prix : " $item["prix"] . " FCFA\n";
  940.                 $texte .= "-------------------------\n";
  941.             }
  942.         }
  943.         $payload = [
  944.             "messaging_product" => "whatsapp",
  945.             "to" => $number,
  946.             "type" => "text",
  947.             "text" => [
  948.                 "body" => $texte
  949.             ]
  950.         ];
  951.         try {
  952.             $response $this->client->request('POST'$apiUrl, [
  953.                 'headers' => [
  954.                     'Authorization' => 'Bearer ' $token,
  955.                     'Content-Type' => 'application/json',
  956.                 ],
  957.                 'json' => $payload,
  958.             ]);
  959.             return $response->toArray();
  960.         } catch (\Exception $e) {
  961.             return ['error' => $e->getMessage()];
  962.         }
  963.     }
  964.     
  965.     public function EnvoyerPrixProduitsAgricoles(array $prixstring $number
  966.     { 
  967.         $apiUrl 'https://graph.facebook.com/v22.0/870067449513702/messages'
  968.         $token 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD'
  969.         // Construction du message 
  970.         if (empty($prix)) 
  971.         { 
  972.             $texte " *Aucun prix de produit agricole trouvé pour cette commune.*"
  973.         } else 
  974.         { 
  975.             $texte " *Prix des produits agricoles*\n\n"
  976.             foreach ($prix as $item
  977.             { 
  978.                 $texte .= " *" $item["produit"] . "*\n"
  979.                 $texte .= " Prix : " $item["prix"] . " FCFA\n"
  980.                 $texte .= "-------------------------\n"
  981.             } 
  982.         } 
  983.         $payload = [ 
  984.             "messaging_product" => "whatsapp"
  985.             "to" => $number
  986.             "type" => "text"
  987.             "text" => [ 
  988.                 "body" => $texte 
  989.             
  990.         ]; 
  991.         try 
  992.         {
  993.             $response $this->client->request('POST'$apiUrl, [ 'headers' => [ 'Authorization' => 'Bearer ' $token'Content-Type' => 'application/json', ], 'json' => $payload, ]); 
  994.             return $response->toArray(); 
  995.         } catch (\Exception $e
  996.         { 
  997.             return ['error' => $e->getMessage()]; 
  998.         } 
  999.     }
  1000.     public function TraiterAgroMeteo($data,$session,$entityManager)
  1001.     {
  1002.         $messages $data['entry'][0]['changes'][0]['value']['messages'][0];
  1003.         $number $messages['from'];
  1004.         $typeMessage $messages['type'];
  1005.         if ($typeMessage === "text") {
  1006.             $texte trim($messages['text']['body']);
  1007.             if ($texte === "Merci" || $texte === "Au revoir") {
  1008.                 $session->setStatut(0);
  1009.                 $session->setDeletedAt(new DateTimeImmutable());
  1010.                 $entityManager->persist($session);
  1011.                 $entityManager->flush();
  1012.                 $this->envoyerSimpleMessage(
  1013.                     "*Session expirée*\nMerci d'avoir utilisé notre service prix.\nÀ très bientôt.",
  1014.                     $number
  1015.                 );
  1016.                 return;
  1017.             }
  1018.         }
  1019.         $agrometeo $entityManager->getRepository(RechercheAgroMeteo::class)->findOneBy(['idSession' => $session->getId(),'statut' => 1]);
  1020.         
  1021.         
  1022.            // Fin de session
  1023.         // if ($agrometeo->getEtape()==3)
  1024.         // {
  1025.         //     $session->setStatut(0);
  1026.         //     $session->setDeletedAt(new DateTimeImmutable());
  1027.         //     $entityManager->flush();
  1028.         //     $this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !", $number);
  1029.         //     return;
  1030.         // }
  1031.         
  1032.         if (!$agrometeo) {
  1033.             $this->envoyerSimpleMessage("Aucune session."$number);
  1034.                 return;
  1035.             // $agrometeo = new RechercheAgroMeteo();
  1036.             // $agrometeo->setIdSession($session);
  1037.             // $agrometeo->setEtape(0);            //etape 0 creation
  1038.             
  1039.             // $agrometeo->setCreatedAt(new DateTimeImmutable());
  1040.             // $agrometeo->setStatut(1);
  1041.             // $entityManager->persist($agrometeo);
  1042.             // $entityManager->flush();
  1043.             // // $text = "👉 Tapez 1 pour *Dates de semis*\n👉 Tapez 2 pour *Poches de sècheresse*\n👉 Tapez 3 pour *Début et fin de saison*\n👉 Tapez 4 pour *Alertes acridiennes et aviaires*\nVeuillez choisir le type d'information souhaité.";
  1044.             // $text = "Veuillez choisir le type d'information souhaité.";
  1045.             // $this->ChoixInformation($text,$number);
  1046.             // return;
  1047.         }
  1048.         if ($agrometeo->getEtape()==0) {
  1049.             if (isset($messages['interactive']['list_reply']['id'])) {
  1050.                 $choix $messages['interactive']['list_reply']['id'];
  1051.             } else {
  1052.                 $this->envoyerSimpleMessage("Veuillez sélectionner un type d'information dans la liste."$number);
  1053.                 return;
  1054.             }
  1055.             
  1056.             $agrometeo->setType($choix);
  1057.             $agrometeo->setEtape(1); // choix type info
  1058.             $entityManager->persist($agrometeo);
  1059.             $entityManager->flush();
  1060.             
  1061.             
  1062.             // $text = "Veuillez saissir la localité souhaitée.";
  1063.             // $this->envoyerSimpleMessage($text, $number);
  1064.             
  1065.         }
  1066.         if ($agrometeo->getEtape()==&& $agrometeo->getType()!=null) {// si etape 1 choix commune fait
  1067.             if ($typeMessage !== "text") {
  1068.                 $this->envoyerSimpleMessage("Veuillez saisir un nom de commune sous forme de texte.",$number);
  1069.                 return;
  1070.             }
  1071.             $texteRecu trim($messages['text']['body']);
  1072.             $listeCommunes $this->AppelApiRechercheCommunes($texteRecu);
  1073.                 if (empty($listeCommunes)) {
  1074.                     $this->envoyerSimpleMessage(
  1075.                         "Aucune commune trouvée pour *$texteRecu*.\nVeuillez saisir un autre nom.",
  1076.                         $number
  1077.                     );
  1078.                     return;
  1079.                 }
  1080.                 $agrometeo->setResultat(json_encode($listeCommunes));
  1081.                 $agrometeo->setEtape(2); //saissi commune
  1082.                 $entityManager->persist($agrometeo);
  1083.                 $entityManager->flush();
  1084.             $this->EnvoyerListeCommunes($listeCommunes$number);
  1085.             return;
  1086.         }
  1087.         if ($agrometeo->getEtape() == 2) {
  1088.             // $this->envoyerSimpleMessage("ok", $number);
  1089.             $userMessage trim($messages['text']['body']);
  1090.             if ($typeMessage !== "text") {
  1091.                 $this->envoyerSimpleMessage("Veuillez saisir un numéro."$number);
  1092.                 return;
  1093.             }
  1094.             if (!ctype_digit($messages['text']['body'])) {
  1095.                 $this->envoyerSimpleMessage("Numéro invalide."$number);
  1096.                 return;
  1097.             }
  1098.             $listeCommunes json_decode($agrometeo->getResultat(), true);
  1099.             $index intval($messages['text']['body']) - 1;
  1100.             if (!isset($listeCommunes[$index])) {
  1101.                 $this->envoyerSimpleMessage("Numéro invalide. Veuillez réessayer."$number);
  1102.                 return;
  1103.             }
  1104.             $commune $listeCommunes[$index];
  1105.             $idCommune=$commune['id'];
  1106.             // Enregistrer dans la base
  1107.             $agrometeo->setCommune($idCommune);
  1108.             $agrometeo->setEtape(3);
  1109.             $entityManager->flush();
  1110.             // Continue selon type
  1111.             if ($agrometeo->getType() == "In_01") {
  1112.                 
  1113.                 $this->EnvoyerDateSemis($idCommune$number);
  1114.                 $agrometeo->setStatut(0);
  1115.                 $agrometeo->setDeletedAt(new DateTimeImmutable());
  1116.                 $session->setStatut(0);
  1117.                 $session->setDeletedAt(new DateTimeImmutable());
  1118.                 $entityManager->persist($session);
  1119.                 $entityManager->flush();
  1120.                 $this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !"$number);
  1121.                 return;
  1122.             }
  1123.             if ($agrometeo->getType() == "In_02") {
  1124.                 
  1125.                 $this->EnvoyerPocheSecheresse($idCommune$number);
  1126.                 $agrometeo->setStatut(0);
  1127.                 $agrometeo->setDeletedAt(new DateTimeImmutable());
  1128.                 $session->setStatut(0);
  1129.                 $session->setDeletedAt(new DateTimeImmutable());
  1130.                 $entityManager->persist($session);
  1131.                 $entityManager->flush();
  1132.                 $this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !"$number);
  1133.                 return;
  1134.             }
  1135.             if ($agrometeo->getType() == "In_03") {
  1136.                 
  1137.                 $this->EnvoyerDateSaison($idCommune$number);
  1138.                 $agrometeo->setStatut(0);
  1139.                 $agrometeo->setDeletedAt(new DateTimeImmutable());
  1140.                 $session->setStatut(0);
  1141.                 $session->setDeletedAt(new DateTimeImmutable());
  1142.                 $entityManager->persist($session);
  1143.                 $entityManager->flush();
  1144.                 $this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !"$number);
  1145.                 return;
  1146.             }
  1147.             if ($agrometeo->getType() == "In_04") {
  1148.                 
  1149.                 $this->EnvoyerAlerte($idCommune$number);
  1150.                 $agrometeo->setStatut(0);
  1151.                 $agrometeo->setDeletedAt(new DateTimeImmutable());
  1152.                 $session->setStatut(0);
  1153.                 $session->setDeletedAt(new DateTimeImmutable());
  1154.                 $entityManager->persist($session);
  1155.                 $entityManager->flush();
  1156.                 $this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !"$number);
  1157.                 return;
  1158.             }
  1159.             return;
  1160.         }
  1161.     
  1162.     }
  1163.     public function EnvoyerDateSemis($idCommune$number)
  1164.     {   
  1165.         // Authentification
  1166.         $auth $this->fonct->execPost('''api/authentification'json_encode(["email"=> "djafarasakinatou@gmail.com","password"=> "l2323"]));
  1167.         //thématiques
  1168.         $responsesemis $this->fonct->execPost($auth['data']['token'],'api/date/semis',json_encode(["id_commune" => $idCommune]));
  1169.             // $this->envoyerSimpleMessage("ok", $number);
  1170.         if (!isset($responsesemis['data'])) {
  1171.             $this->envoyerSimpleMessage("Aucune donnée trouvée ."$number);
  1172.             return;
  1173.         }
  1174.         $msg "Information disponible:\n";
  1175.         foreach ($responsesemis['data'] as $semis) {
  1176.             $msg .= "*{$semis['information']}*\n\n";
  1177.         }
  1178.         $msg .= "\nPour arrêter tapez *merci* ou *au revoir*.";
  1179.         // Envoyer
  1180.         $this->envoyerSimpleMessage($msg$number);
  1181.     }
  1182.     public function EnvoyerPocheSecheresse($idCommune$number)
  1183.     {   
  1184.         
  1185.         // Authentification
  1186.         $auth $this->fonct->execPost('''api/authentification'json_encode(["email"=> "djafarasakinatou@gmail.com","password"=> "l2323"]));
  1187.         //thématiques
  1188.         $responsesemis $this->fonct->execPost($auth['data']['token'],'api/poche/secheresse',json_encode(["id_commune" => $idCommune]));
  1189.             // $this->envoyerSimpleMessage("ok", $number);
  1190.         // 🔍 DEBUG : voir ce que retourne l'API
  1191.         //$this->envoyerSimpleMessage("DEBUG : \n" . json_encode($responsesemis), $number);
  1192.         if (!isset($responsesemis['data'])) {
  1193.             $this->envoyerSimpleMessage("Aucune donnée trouvée ."$number);
  1194.             return;
  1195.         }
  1196.         $msg "Information disponible:\n";
  1197.         foreach ($responsesemis['data'] as $semis) {
  1198.             $msg .= "*{$semis['information']}*\n\n";
  1199.         }
  1200.         $msg .= "\nPour arrêter tapez *merci* ou *au revoir*.";
  1201.         // Envoyer
  1202.         $this->envoyerSimpleMessage($msg$number);
  1203.     }
  1204.        public function EnvoyerDateSaison($idCommune$number)
  1205.     {   
  1206.         // Authentification
  1207.         $auth $this->fonct->execPost('''api/authentification'json_encode(["email"=> "djafarasakinatou@gmail.com","password"=> "l2323"]));
  1208.         //thématiques
  1209.         $responsesemis $this->fonct->execPost($auth['data']['token'],'api/date/saison',json_encode(["id_commune" => $idCommune]));
  1210.             // $this->envoyerSimpleMessage("ok", $number);
  1211.         if (!isset($responsesemis['data'])) {
  1212.             $this->envoyerSimpleMessage("Aucune donnée trouvée ."$number);
  1213.             return;
  1214.         }
  1215.         $msg "Information disponible:\n";
  1216.         foreach ($responsesemis['data'] as $semis) {
  1217.             $msg .= "*{$semis['information']}*\n\n";
  1218.         }
  1219.         $msg .= "\nPour arrêter tapez *merci* ou *au revoir*.";
  1220.         // Envoyer
  1221.         $this->envoyerSimpleMessage($msg$number);
  1222.     }
  1223.     public function EnvoyerAlerte($idCommune$number)
  1224.     {   
  1225.         // Authentification
  1226.         $auth $this->fonct->execPost('''api/authentification'json_encode(["email"=> "djafarasakinatou@gmail.com","password"=> "l2323"]));
  1227.         //thématiques
  1228.         $responsesemis $this->fonct->execPost($auth['data']['token'],'api/alerte',json_encode(["id_commune" => $idCommune]));
  1229.             // $this->envoyerSimpleMessage("ok", $number);
  1230.         if (!isset($responsesemis['data'])) {
  1231.             $this->envoyerSimpleMessage("Aucune donnée trouvée ."$number);
  1232.             return;
  1233.         }
  1234.         $msg "Information disponible:\n";
  1235.         foreach ($responsesemis['data'] as $semis) {
  1236.             $msg .= "*{$semis['information']}*\n\n";
  1237.         }
  1238.         $msg .= "\nPour arrêter tapez *merci* ou *au revoir*.";
  1239.         // Envoyer
  1240.         $this->envoyerSimpleMessage($msg$number);
  1241.     }
  1242.     public function TraiterAppuisConseil($data$session$entityManager)
  1243.     {
  1244.         $messages $data['entry'][0]['changes'][0]['value']['messages'][0];
  1245.         $number $messages['from'];
  1246.         $typeMessage $messages['type'];
  1247.         if ($typeMessage === "text") {
  1248.             $texte trim($messages['text']['body']);
  1249.             if ($texte === "Merci" || $texte === "Au revoir") {
  1250.                 $session->setStatut(0);
  1251.                 $session->setDeletedAt(new DateTimeImmutable());
  1252.                 $entityManager->persist($session);
  1253.                 $entityManager->flush();
  1254.                 $this->envoyerSimpleMessage(
  1255.                     "*Session expirée*\nMerci d'avoir utilisé notre service prix.\nÀ très bientôt.",
  1256.                     $number
  1257.                 );
  1258.                 return;
  1259.             }
  1260.         }
  1261.         $apuisconseil $entityManager->getRepository(RechercheAppuisConseil::class)->findOneBy(['idSession' => $session->getId(), 'statut' => 1]);
  1262.         if (!$apuisconseil) {
  1263.             $this->envoyerSimpleMessage("Aucune session."$number);
  1264.                 return;
  1265.         }
  1266.         if ($apuisconseil->getEtape() == 0) {
  1267.             // Récupère le choix domaine depuis interactive ou texte
  1268.             
  1269.             if (isset($messages['interactive']['list_reply']['id'])) {
  1270.                 $choix $messages['interactive']['list_reply']['id'];
  1271.             } else {
  1272.                 $this->envoyerSimpleMessage("Veuillez sélectionner un type d'information dans la liste."$number);
  1273.                 return;
  1274.             }
  1275.             $theme $this->thematiqueTrouver($choix);
  1276.                 if (empty($theme)) {
  1277.                     $this->envoyerSimpleMessage(
  1278.                         "Aucun thème trouvé.",
  1279.                         $number
  1280.                     );
  1281.                     return;
  1282.                 }
  1283.             $apuisconseil->setResultat(json_encode($theme));
  1284.             $apuisconseil->setDomaine($choix);
  1285.             $apuisconseil->setEtape(1); // étape thématique
  1286.             $entityManager->flush();
  1287.             $this->EnvoyerListeThematique($choix$number);
  1288.             return;
  1289.         }
  1290.         if ($apuisconseil->getEtape() == && $typeMessage == "text") {
  1291.             
  1292.             
  1293.             $choixThematique trim($messages['text']['body']);
  1294.            
  1295.             // Vérifie que le choix est un ID numérique ou valide
  1296.             if (!ctype_digit($choixThematique)) {
  1297.                 $this->envoyerSimpleMessage("Veuillez saisir un numéro valide."$number);
  1298.                 return;
  1299.             }
  1300.             
  1301.             $listetheme json_decode($apuisconseil->getResultat(), true);
  1302.             $index intval($choixThematique) - 1;
  1303.             if (!isset($listetheme[$index])) {
  1304.                 $this->envoyerSimpleMessage("Numéro invalide. Veuillez réessayer."$number);
  1305.                 return;
  1306.             }
  1307.             $theme $listetheme[$index];
  1308.             $idTheme=$theme['id'];
  1309.             $apuisconseil->setThematique($idTheme);
  1310.             $apuisconseil->setEtape(2); // fin
  1311.             $entityManager->flush();
  1312.             
  1313.             $this->envoyerFichierTheme($number$idTheme);
  1314.             sleep(2);
  1315.             $this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !"$number);
  1316.             $apuisconseil->setStatut(0);
  1317.             $apuisconseil->setDeletedAt(new DateTimeImmutable());
  1318.             $session->setStatut(0);
  1319.             $session->setDeletedAt(new DateTimeImmutable());
  1320.             $entityManager->flush();
  1321.             return;
  1322.         }
  1323.     }
  1324.     #[Route('/communication'name'app_communication'methods: ['GET''POST'])]
  1325.     public function index(Request $requestMessageRepository $messageRepository): Response
  1326.     {
  1327.         $message = new Message();
  1328.         $form $this->createForm(MessageType::class, $message);
  1329.         $form->handleRequest($request);  
  1330.         if ($form->isSubmitted() && $form->isValid()) {
  1331.             $imageFiles $form->get('image')->getData();
  1332.             $telephone $form->get('telephone')->getData();
  1333.             $contenus $form->get('contenus')->getData();
  1334.             $titre $form->get('titre')->getData();
  1335.             if ($imageFiles) {
  1336.                 foreach ($imageFiles as $imageFile) {
  1337.                     $newFilename uniqid().'.'.$imageFile->guessExtension();
  1338.                     try {
  1339.                         $imageFile->move(
  1340.                             $this->getParameter('messages_images_directory'),
  1341.                             $newFilename
  1342.                         );
  1343.                     } catch (FileException $e) {
  1344.                         $this->addFlash('error''Impossible de télécharger une image.');
  1345.                         continue;
  1346.                     }
  1347.                     $message->addImage($newFilename);
  1348.                 }
  1349.             }
  1350.             $message->setCreatedAt(new \DateTimeImmutable());
  1351.             $message->setStatus(1);
  1352.             $message->setIdUser($this->getUser());
  1353.                 // dd($message);
  1354.             $messageRepository->add($messagetrue);
  1355.             
  1356.             $resultat $this->envoyerMessage("227".$telephone,$contenus,$titre);
  1357.             // $resultat = $this->envoyerSimpleMessage($contenus, "227".$telephone);
  1358.             if ($imageFiles) {
  1359.             $resultat $this->envoyerMessagePlusDocument("227".$telephone"1" );
  1360.             }
  1361.             return $this->redirectToRoute('app_communication', [], Response::HTTP_SEE_OTHER);
  1362.         }
  1363.         $messages $messageRepository->findBy(
  1364.             ['status' => 1],
  1365.             ['createdAt' => 'DESC']
  1366.         );
  1367.         
  1368.         $this->addFlash('success''Message envoyé avec succès !');    
  1369.         return $this->render('message/index.html.twig', [
  1370.             'messages' => $messages,
  1371.             'form' => $form->createView(),
  1372.         ]);
  1373.     }
  1374.     #[Route('/message/{id}'name'app_message_show'methods: ['GET''POST'])]
  1375.     public function show(Message $messageMessageRepository $messageRepository): Response
  1376.     {
  1377.         
  1378.         return $this->render('message/detail.html.twig', [
  1379.             
  1380.             'messages' => $messageRepository->findBy(
  1381.             ['status' => 1],
  1382.             ['createdAt' => 'DESC']
  1383.         ),
  1384.             'message' => $message,
  1385.         ]);
  1386.     }
  1387.     public function envoyerSimpleMessage(string $contenusstring $numero)
  1388.     {
  1389.         $numero ltrim($numero'+');
  1390.         $apiUrl 'https://graph.facebook.com/v22.0/1037760686078257/messages';
  1391.         $token 'EAAesTlijMGcBQZBCYGuMKGO9Iqz0NQnaKVJPdyV94WmU5kfdLYE5PzgtO67IIL6qaiJMJ8KFLRACc5q7ZCsfCqQi9BmAuxQN88EDxhyhdZClUc16NdZB0TNXVoFWtjZCveKKT9R3ebxRnpYeePhIo0xsYtoQ8tZBwRBTWovkWmZBADso9xcrc3uEtEhCL8KRGKaaTkGeqhVuV2yzfWsVZAHpXzkx4lzwHZCccRyTeZCiDtAkFpoaTiXyTD2sTbLyN5ZC0VZCesDA5TezyKfR2n1vWmo3G98PIgZDZD';
  1392.         $data = [
  1393.             "messaging_product" => "whatsapp",
  1394.             "to" => $numero,
  1395.             "type" => "text",
  1396.             "text" => [
  1397.                 "preview_url" => false,
  1398.                 "body" => $contenus
  1399.             ]
  1400.         ];
  1401.         $ch curl_init();
  1402.         curl_setopt_array($ch, [
  1403.             CURLOPT_URL => $apiUrl,
  1404.             CURLOPT_RETURNTRANSFER => true,
  1405.             CURLOPT_POST => true,
  1406.             CURLOPT_TIMEOUT => 10,
  1407.             CURLOPT_HTTPHEADER => [
  1408.                 "Authorization: Bearer $token",
  1409.                 "Content-Type: application/json"
  1410.             ],
  1411.             CURLOPT_POSTFIELDS => json_encode($data)
  1412.         ]);
  1413.         $response curl_exec($ch);
  1414.         $httpCode curl_getinfo($chCURLINFO_HTTP_CODE);
  1415.         if (curl_errno($ch)) {
  1416.             dump("Curl error: " curl_error($ch));
  1417.         }
  1418.         curl_close($ch);
  1419.         dump("HTTP CODE: " $httpCode);
  1420.         dump("RESPONSE: " $response);
  1421.         return $response;
  1422.     }
  1423.     // public function envoyerSimpleMessage(string $contenus,string $numero)
  1424.     // {
  1425.     //     $apiUrl = 'https://graph.facebook.com/v22.0/1037760686078257/messages';
  1426.     //     $token =  'EAAesTlijMGcBQZBCYGuMKGO9Iqz0NQnaKVJPdyV94WmU5kfdLYE5PzgtO67IIL6qaiJMJ8KFLRACc5q7ZCsfCqQi9BmAuxQN88EDxhyhdZClUc16NdZB0TNXVoFWtjZCveKKT9R3ebxRnpYeePhIo0xsYtoQ8tZBwRBTWovkWmZBADso9xcrc3uEtEhCL8KRGKaaTkGeqhVuV2yzfWsVZAHpXzkx4lzwHZCccRyTeZCiDtAkFpoaTiXyTD2sTbLyN5ZC0VZCesDA5TezyKfR2n1vWmo3G98PIgZDZD';
  1427.         
  1428.     //     $data = [
  1429.     //         "messaging_product" => "whatsapp",
  1430.     //         "recipient_type" => "individual",
  1431.     //         "to" => "$numero", // numéro du destinataire
  1432.     //         "type" => "text",
  1433.     //         "text" => [
  1434.     //             "preview_url" => false,
  1435.     //             "body" => $contenus
  1436.     //         ]
  1437.     //     ];
  1438.     //     $ch = curl_init();
  1439.     //     curl_setopt_array($ch, [
  1440.     //         CURLOPT_URL => $apiUrl,
  1441.     //         CURLOPT_RETURNTRANSFER => true,
  1442.     //         CURLOPT_POST => true,
  1443.     //         CURLOPT_HTTPHEADER => [
  1444.     //             "Authorization: Bearer $token",
  1445.     //             "Content-Type: application/json"
  1446.     //         ],
  1447.     //         CURLOPT_POSTFIELDS => json_encode($data)
  1448.     //     ]);
  1449.     //     $response = curl_exec($ch);
  1450.     //     curl_close($ch);
  1451.     // }
  1452.     public function ChoixInformation(string $textstring $number)
  1453.     {
  1454.         $apiUrl 'https://graph.facebook.com/v22.0/870067449513702/messages';
  1455.         $token 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
  1456.         $payload = [
  1457.             "messaging_product" => "whatsapp",
  1458.             "to" => $number,
  1459.             "type" => "interactive",
  1460.             "interactive" => [
  1461.                 "type" => "list",
  1462.                 "body" => [
  1463.                     "text" => $text
  1464.                 ],
  1465.                 "footer" => [
  1466.                     "text" => "Pour arrêter le processus tapez merci ou au revoir"
  1467.                 ],
  1468.                 "action" => [
  1469.                     "button" => "Choisir un type",
  1470.                     "sections" => [
  1471.                         [
  1472.                             "title" => "Type information",
  1473.                             "rows" => [
  1474.                                 [
  1475.                                     "id" => "In_01",
  1476.                                     "title" => "SEMIS",
  1477.                                     "description" => "Dates de semis"
  1478.                                 ],
  1479.                                 [
  1480.                                     "id" => "In_02",
  1481.                                     "title" => "SECHERESSE",
  1482.                                     "description" => "Poches de sècheresse"
  1483.                                 ],
  1484.                                 [
  1485.                                     "id" => "In_03",
  1486.                                     "title" => "SAISON",
  1487.                                     "description" => "Début et fin de la saison"
  1488.                                 ],
  1489.                                 [
  1490.                                     "id" => "In_04",
  1491.                                     "title" => "ALERTE",
  1492.                                     "description" => "Alerte sur l’invasion acridienne et aviaire"
  1493.                                 ]
  1494.                             ]
  1495.                         ]
  1496.                     ]
  1497.                 ]
  1498.             ]
  1499.         ];
  1500.         try {
  1501.             $response $this->client->request('POST'$apiUrl, [
  1502.                 'headers' => [
  1503.                     'Authorization' => 'Bearer ' $token,
  1504.                     'Content-Type' => 'application/json',
  1505.                 ],
  1506.                 'json' => $payload,
  1507.             ]);
  1508.             return $response->toArray();
  1509.         } catch (\Exception $e) {
  1510.             return ['error' => $e->getMessage()];
  1511.         }
  1512.     }
  1513.     public function MessageChoixService(string $textstring $number)
  1514.     {
  1515.         $apiUrl 'https://graph.facebook.com/v22.0/870067449513702/messages';
  1516.         $token 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
  1517.         $payload = [
  1518.             "messaging_product" => "whatsapp",
  1519.             "to" => $number,
  1520.             "type" => "interactive",
  1521.             "interactive" => [
  1522.                 "type" => "list",
  1523.                 "body" => [
  1524.                     "text" => $text
  1525.                 ],
  1526.                 "footer" => [
  1527.                     "text" => "Pour arrêter le processus tapez merci ou au revoir"
  1528.                 ],
  1529.                 "action" => [
  1530.                     "button" => "Choisir un service",
  1531.                     "sections" => [
  1532.                         [
  1533.                             "title" => "Services disponibles",
  1534.                             "rows" => [
  1535.                                 [
  1536.                                     "id" => "Sc_001",
  1537.                                     "title" => "AGRO METEO",
  1538.                                     "description" => "Prévisions météorologiques d'une localité du Niger"
  1539.                                 ],
  1540.                                 [
  1541.                                     "id" => "Sc_002",
  1542.                                     "title" => "APPUIS CONSEIL",
  1543.                                     "description" => "Conseils et assistance dans divers domaines"
  1544.                                 ],
  1545.                                 [
  1546.                                     "id" => "Sc_003",
  1547.                                     "title" => "PRIX",
  1548.                                     "description" => "Prix des animaux et produits agricoles dans les marchés du Niger"
  1549.                                 ]
  1550.                             ]
  1551.                         ]
  1552.                     ]
  1553.                 ]
  1554.             ]
  1555.         ];
  1556.         try {
  1557.             $response $this->client->request('POST'$apiUrl, [
  1558.                 'headers' => [
  1559.                     'Authorization' => 'Bearer ' $token,
  1560.                     'Content-Type' => 'application/json',
  1561.                 ],
  1562.                 'json' => $payload,
  1563.             ]);
  1564.             return $response->toArray();
  1565.         } catch (\Exception $e) {
  1566.             return ['error' => $e->getMessage()];
  1567.         }
  1568.     }
  1569.     public function ChoixDomaine(string $number)
  1570.     {
  1571.         
  1572.        //on recupere la connection
  1573.         $all=[
  1574.             "email"=> "djafarasakinatou@gmail.com",
  1575.             "password"=> "l2323"
  1576.         ];
  1577.         $dataPost=json_encode($all);
  1578.         $chemin='api/authentification';
  1579.         $response=$this->fonct->execPost('',$chemin,$dataPost);
  1580.        
  1581.         //on recupere les domaines
  1582.         $cheminDomaine='api/appuis/conseil/domaine';
  1583.         $responseDomaine=$this->fonct->execGet($response['data']['token'],$cheminDomaine);
  1584.         
  1585.         $messageListe = array();
  1586.         $text="Veuillez choisir un domaine";
  1587.         foreach ($responseDomaine['data'] as $domaine) {
  1588.             
  1589.             $messageListe[] = [
  1590.                             "id" => $domaine['id'],
  1591.                             "title" => $domaine['libelle']
  1592.             ];
  1593.         }
  1594.     
  1595.         $apiUrl 'https://graph.facebook.com/v22.0/870067449513702/messages';
  1596.         $token 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
  1597.         $payload = [
  1598.             "messaging_product" => "whatsapp",
  1599.             "to" => $number,
  1600.             "type" => "interactive",
  1601.             "interactive" => [
  1602.                 "type" => "list",
  1603.                 "body" => [
  1604.                     "text" => $text
  1605.                 ],
  1606.                 "footer" => [
  1607.                     "text" => "Pour arrêter le processus tapez merci ou au revoir"
  1608.                 ],
  1609.                 "action" => [
  1610.                     "button" => "Choisir un domaine",
  1611.                     "sections" => [
  1612.                         [
  1613.                             "title" => "domaine disponibles",
  1614.                             "rows" => $messageListe
  1615.                         ]
  1616.                     ]
  1617.                 ]
  1618.             ]
  1619.         ];
  1620.         try {
  1621.             $response $this->client->request('POST'$apiUrl, [
  1622.                 'headers' => [
  1623.                     'Authorization' => 'Bearer ' $token,
  1624.                     'Content-Type' => 'application/json',
  1625.                 ],
  1626.                 'json' => $payload,
  1627.             ]);
  1628.             return $response->toArray();
  1629.         } catch (\Exception $e) {
  1630.             return ['error' => $e->getMessage()];
  1631.         }
  1632.     }
  1633.     public function EnvoyerListeThematique($choix$number)
  1634.     {
  1635.         // Authentification
  1636.         $auth $this->fonct->execPost('''api/authentification'json_encode(["email"=> "djafarasakinatou@gmail.com","password"=> "l2323"]));
  1637.         //thématiques
  1638.         $responseThematique $this->fonct->execPost($auth['data']['token'],'api/appuis/conseil/theme',json_encode(["id_domaine" => $choix]));
  1639.         //$this->envoyerSimpleMessage("DEBUG : \n" . json_encode($responseThematique), $number);
  1640.         if (!isset($responseThematique['data'])) {
  1641.             $this->envoyerSimpleMessage("Aucune donnée trouvée pour cette commune."$number);
  1642.             return;
  1643.         }
  1644.         // texte
  1645.         $msg "📚 *Veuillez choisir une thématique :*\n\n";
  1646.         foreach ($responseThematique['data'] as $theme) {
  1647.             $msg .= "👉 Tapez *{$theme['N°']}* pour *{$theme['libelle']}*\n";
  1648.         }
  1649.         $msg .= "\nPour arrêter tapez *merci* ou *au revoir*.";
  1650.         // Envoyer
  1651.         $this->envoyerSimpleMessage($msg$number);
  1652.     }
  1653.     public function thematiqueTrouver($domaine): array 
  1654.     {  
  1655.         // Authentification
  1656.         $auth $this->fonct->execPost('','api/authentification',json_encode([
  1657.                 "email"=> "djafarasakinatou@gmail.com",
  1658.                 "password"=> "l2323"
  1659.             ])
  1660.         );
  1661.         // Vérification authentification
  1662.         if (!isset($auth['data']['token'])) {
  1663.             return [];
  1664.         }
  1665.         $token $auth['data']['token'];
  1666.         // Récupération thématiques
  1667.         $response $this->fonct->execPost($token,'api/appuis/conseil/theme',json_encode(["id_domaine" => $domaine]));
  1668.         // Vérification statuts
  1669.         if (!isset($response['status']) || $response['status'] !== 200) {
  1670.             return [];
  1671.         }
  1672.         // Retour du tableau des thématiques
  1673.         return $response['data'] ?? [];
  1674.     }
  1675.     #[Route('/envoyer/fichier'name'app_envoyer_fichier'methods: ['POST'])]
  1676.     public function envoyerFichier(Request $requestEntityManagerInterface $entityManagerUserRepository $UserRepository): Response
  1677.     {
  1678.         $data json_decode($request->getContent(), true);
  1679.         $obligatoire = ['id_theme','numero'];
  1680.         foreach ($obligatoire as $champs) {
  1681.             if (empty($data[$champs])) {
  1682.                 return $this->json([
  1683.                     'status' => 400,
  1684.                     'message' => 'failed',
  1685.                     'data' => ['error_message' => "Le champ $champs est obligatoire."],
  1686.                 ]);
  1687.             }
  1688.         }
  1689.         $apiUrl 'https://graph.facebook.com/v22.0/870067449513702/messages';
  1690.         $token  'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
  1691.         // Authentification interne
  1692.         $auth $this->fonct->execPost('''api/authentification'json_encode([
  1693.             "email"=> "djafarasakinatou@gmail.com",
  1694.             "password"=> "l2323"
  1695.         ]));
  1696.         // Récupération des fichiers
  1697.         $responsefichiers $this->fonct->execPost(
  1698.             $auth['data']['token'],
  1699.             'api/appuis/conseil/fichier',
  1700.             json_encode(["id_theme"=> $data['id_theme']])
  1701.         );
  1702.         if (!isset($responsefichiers['data']) || empty($responsefichiers['data'])) {
  1703.             return $this->json(['status' => 400'message' => 'Aucun fichier trouvé']);
  1704.         }
  1705.         //dd($responsefichiers);
  1706.         $dataFichier = [];
  1707.         // $i=0;
  1708.         foreach ($responsefichiers['data'] as $item) {
  1709.             
  1710.             $dataFichier[] = [
  1711.                 'conseil'=>$item['conseil'],
  1712.                 'fichier'=>$item['fichier'],
  1713.                 'semaine'=>$item['semaine'],
  1714.                 'date_ajout'=>$item['date_ajout'],
  1715.             ];
  1716.             $extension pathinfo($item['fichier'], PATHINFO_EXTENSION);
  1717.             // dd($extension);
  1718.             $payload = [
  1719.                 "to" => $data['numero'],
  1720.                 "type" => "template",
  1721.                 "messaging_product" => "whatsapp",
  1722.                 "template" => [
  1723.                     "name" => "model_garbal_format_document",
  1724.                     "language" => ["code" => "fr"],
  1725.                     "components" => [
  1726.                         [
  1727.                             "type" => "header",
  1728.                             "parameters" => [
  1729.                                 [
  1730.                                     "type" => "document",
  1731.                                     "document" => [
  1732.                                         "link" => $item['fichier'],
  1733.                                         "filename" => $item['conseil']
  1734.                                     ]
  1735.                                 ]
  1736.                             ]
  1737.                         ],
  1738.                         [
  1739.                             "type" => "body",
  1740.                             "parameters" => [
  1741.                                 [
  1742.                                     "type" => "text",
  1743.                                     "text" => $item['conseil']
  1744.                                 ]
  1745.                             ]
  1746.                         ]
  1747.                     ]
  1748.                 ]
  1749.             ];
  1750.             $ch curl_init();
  1751.             curl_setopt($chCURLOPT_URL$apiUrl);
  1752.             curl_setopt($chCURLOPT_HTTPHEADER, [
  1753.                 'Authorization: Bearer '.$token,
  1754.                 'Content-Type: application/json'
  1755.             ]);
  1756.             curl_setopt($chCURLOPT_POSTFIELDSjson_encode($payload));
  1757.             curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  1758.             $response curl_exec($ch);
  1759.             $error curl_error($ch);
  1760.             curl_close($ch);
  1761.             file_put_contents("whatsapp_response.log""RESPONSE: ".$response." | ERROR: ".$error.PHP_EOLFILE_APPEND);
  1762.             // usleep(300000); // pause 0.3s pour ne pas se faire bloquer
  1763.         }
  1764.         
  1765.         return $this->json([
  1766.             'status' => 200,
  1767.             'message' => 'Fichiers envoyés avec succès'
  1768.             // 'data' => $dataFichier
  1769.         ]);
  1770.     }
  1771.     public function envoyerFichierTheme($numero$id_theme)
  1772.     {
  1773.         $apiUrl 'https://graph.facebook.com/v22.0/870067449513702/messages';
  1774.         $token  'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
  1775.         // Authentification interne
  1776.         $auth $this->fonct->execPost('''api/authentification'json_encode([
  1777.             "email"=> "djafarasakinatou@gmail.com",
  1778.             "password"=> "l2323"
  1779.         ]));
  1780.         //$this->envoyerSimpleMessage("Aucune donnée trouvée pour cette commune.", $numero);
  1781.             
  1782.         // Récupération des fichiers
  1783.         $responsefichiers $this->fonct->execPost(
  1784.             $auth['data']['token'],
  1785.             'api/appuis/conseil/fichier',
  1786.             json_encode(["id_theme"=> $id_theme])
  1787.         );
  1788.         //$this->envoyerSimpleMessage("DEBUG : \n" . json_encode($responsefichiers), $numero);
  1789.         if (!isset($responsefichiers['data']) || empty($responsefichiers['data'])) {
  1790.             $this->envoyerSimpleMessage("Aucune donnée trouvée ."$numero);
  1791.             return;
  1792.         }
  1793.         $this->envoyerSimpleMessage("Veuillez patienter quelques instants, les fichiers sont en cours d'envoi…"$numero);
  1794.         //dd($responsefichiers);
  1795.         $dataFichier = [];
  1796.         // $i=0;
  1797.         foreach ($responsefichiers['data'] as $item) {
  1798.            // $this->envoyerSimpleMessage("TEST : ".$item['fichier'], $numero);
  1799.             $dataFichier[] = [
  1800.                 'conseil'=>$item['conseil'],
  1801.                 'fichier'=>$item['fichier'],
  1802.                 'semaine'=>$item['semaine'],
  1803.                 'date_ajout'=>$item['date_ajout'],
  1804.             ];
  1805.             $extension pathinfo($item['fichier'], PATHINFO_EXTENSION);
  1806.             // dd($extension);
  1807.             $payload = [
  1808.                 "to" => $numero,
  1809.                 "type" => "template",
  1810.                 "messaging_product" => "whatsapp",
  1811.                 "template" => [
  1812.                     "name" => "model_garbal_format_document",
  1813.                     "language" => ["code" => "fr"],
  1814.                     "components" => [
  1815.                         [
  1816.                             "type" => "header",
  1817.                             "parameters" => [
  1818.                                 [
  1819.                                     "type" => "document",
  1820.                                     "document" => [
  1821.                                         "link" => $item['fichier'],
  1822.                                         "filename" => $item['conseil']
  1823.                                     ]
  1824.                                 ]
  1825.                             ]
  1826.                         ],
  1827.                         [
  1828.                             "type" => "body",
  1829.                             "parameters" => [
  1830.                                 [
  1831.                                     "type" => "text",
  1832.                                     "text" => $item['conseil']
  1833.                                 ]
  1834.                             ]
  1835.                         ]
  1836.                     ]
  1837.                 ]
  1838.             ];
  1839.             $ch curl_init();
  1840.             curl_setopt($chCURLOPT_URL$apiUrl);
  1841.             curl_setopt($chCURLOPT_HTTPHEADER, [
  1842.                 'Authorization: Bearer '.$token,
  1843.                 'Content-Type: application/json'
  1844.             ]);
  1845.             curl_setopt($chCURLOPT_POSTFIELDSjson_encode($payload));
  1846.             curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  1847.             $response curl_exec($ch);
  1848.             $error curl_error($ch);
  1849.             curl_close($ch);
  1850.             file_put_contents("whatsapp_response.log""RESPONSE: ".$response." | ERROR: ".$error.PHP_EOLFILE_APPEND);
  1851.             // usleep(300000); // pause 0.3s pour ne pas se faire bloquer
  1852.         }
  1853.     }
  1854.     
  1855.      public function envoyerMessagePlusDocument(string $numerostring $nombre)
  1856.     {
  1857.         $apiUrl 'https://graph.facebook.com/v22.0/870067449513702/messages';
  1858.         $token =  'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcS';
  1859.         
  1860.         $payload = [
  1861.             "messaging_product" => "whatsapp",
  1862.             "to" => "$numero",
  1863.             "type" => "template",
  1864.             "template" => [
  1865.                 "name" => "model_garbal_format_document ",
  1866.                 "language" => ["code" => "FR"],
  1867.                 "components" => [
  1868.                     [
  1869.                         "type" => "body",
  1870.                         "parameters" => [
  1871.                             ["type" => "text""text" => $nombre],
  1872.                         ],
  1873.                     ],
  1874.                 ],
  1875.             ],
  1876.         ];
  1877.         try {
  1878.             $response $this->client->request('POST'$apiUrl, [
  1879.                 'headers' => [
  1880.                     'Authorization' => 'Bearer ' $token,
  1881.                     'Content-Type' => 'application/json',
  1882.                 ],
  1883.                 'json' => $payload,
  1884.             ]);
  1885.             return $response->toArray(); 
  1886.         } catch (\Exception $e) {
  1887.             return ['error' => $e->getMessage()];
  1888.         }
  1889.     }
  1890.     
  1891.     public function envoyerMessage(string $numerostring $contenus ,string $titre)
  1892.     {
  1893.             
  1894.         $apiUrl 'https://graph.facebook.com/v22.0/870067449513702/messages';
  1895.         $token =  'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
  1896.         
  1897.         $payload = [
  1898.             "messaging_product" => "whatsapp",
  1899.             "to" => "$numero",
  1900.             "type" => "template",
  1901.             "template" => [
  1902.                 "name" => "model_garbal_message",
  1903.                 "language" => ["code" => "fr"],
  1904.                 "components" => [
  1905.                         [
  1906.                         "type" => "header",
  1907.                         "parameters" => [
  1908.                             [
  1909.                                 "type" => "text",
  1910.                                 "text" => $titre
  1911.                             ]
  1912.                         ]
  1913.                     ],
  1914.                     [
  1915.                         "type" => "body",
  1916.                         "parameters" => [
  1917.                             ["type" => "text""text" => $contenus],
  1918.             
  1919.                         ],
  1920.                     ],
  1921.                 ],
  1922.             ],
  1923.         ];
  1924.         try {
  1925.             $response $this->client->request('POST'$apiUrl, [
  1926.                 'headers' => [
  1927.                     'Authorization' => 'Bearer ' $token,
  1928.                     'Content-Type' => 'application/json',
  1929.                 ],
  1930.                 'json' => $payload,
  1931.             ]);
  1932.             return $response->toArray(); 
  1933.         } catch (\Exception $e) {
  1934.             return ['error' => $e->getMessage()];
  1935.         }
  1936.     }
  1937.     private function validateToken(Request $requestJWTEncoderInterface $JWTDecodeManagerEntityManagerInterface $entityManagerUserRepository $UserRepository)
  1938.     {
  1939.         $authorizationHeader $request->headers->get('Authorization');
  1940.         if (!$authorizationHeader) {
  1941.             return new JsonResponse(['status' => 401'message' => 'Token non fourni'], 401);
  1942.         }
  1943.         $tokenParts explode(' '$authorizationHeader);
  1944.         if (count($tokenParts) !== || $tokenParts[0] !== 'Bearer') {
  1945.             return new JsonResponse(['status' => 401'message' => 'Format du token invalide'], 401);
  1946.         }
  1947.         $token $tokenParts[1];
  1948.         try {
  1949.             $userData $JWTDecodeManager->decode($token);
  1950.         } catch (\Exception $e) {
  1951.             return new JsonResponse(['status' => 401'message' => 'Token invalide'], 401);
  1952.         }
  1953.         if (!isset($userData['username'])) {
  1954.             return new JsonResponse(['status' => 401'message' => 'Token mal formé (username manquant)'], 401);
  1955.         }
  1956.         // dd($userData);
  1957.         $user $UserRepository->findOneBy(['email' => $userData['username']]);
  1958.         
  1959.         if (!$user) {
  1960.             return new JsonResponse(['status' => 401'message' => 'Utilisateur non trouvé'], 401);
  1961.         }
  1962.         if ($user->getStatut() != 1) {
  1963.             return new JsonResponse(['status' => 401'message' => 'Compte inactif'], 401);
  1964.         }
  1965.         if (isset($userData['exp']) && $userData['exp'] < time()) {
  1966.         return new JsonResponse(['status' => 401'message' => 'Token expiré'], 401);
  1967.         }
  1968.         // Tout est bon, on retourne les infos de l'utilisateur
  1969.         return [
  1970.             'id'    => $user->getId(),
  1971.             'role'  => $user->getRoles(),
  1972.             'email' => $user->getEmail()
  1973.         ];
  1974.     }
  1975. }