src/Controller/MessageController.php line 43

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\MessageRepository;
  10. use Doctrine\ORM\EntityManagerInterface;
  11. use Symfony\Component\HttpFoundation\Request;
  12. use Symfony\Component\HttpFoundation\File\Exception\FileException;
  13. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  14. use App\Entity\Client;
  15. use App\Entity\RechercheAppuisConseil;
  16. use Symfony\Component\HttpFoundation\JsonResponse;
  17. use Lexik\Bundle\JWTAuthenticationBundle\Encoder\JWTEncoderInterface;
  18. use App\Repository\ClientRepository;
  19. use App\Entity\Session;
  20. use App\Repository\RechercheAgroMeteoRepository;
  21. use App\Repository\RechercheAppuisConseilRepository;
  22. use App\Entity\RechercheAgroMeteo;
  23. use App\Repository\RecherchePrixRepository;
  24. use App\Entity\RecherchePrix;
  25. use App\Repository\SessionRepository;
  26. use App\Fonctions\Fonctions;
  27. use App\Repository\UserRepository;
  28. use DateTimeImmutable;
  29. class MessageController extends AbstractController
  30. {
  31.     private $client;
  32.     public function __construct(SessionInterface $session,HttpClientInterface $client,Fonctions $fonct)
  33.     {
  34.         $this->client $client;
  35.         $this->fonct $fonct;
  36.         $this->session $session;
  37.        
  38.     }
  39.     
  40.     // try {
  41.     //         $accessToken = "JCSDIUVHDJFVBEUDYVBDFJHKBVCSDFJHBVCJDYHS";
  42.     //          $token = $request->query->get('hub_verify_token');
  43.     //         $challenge = $request->query->get('hub_challenge');
  44.     //        // dd($token,$challenge);
  45.     //         if ($challenge !== null && $token !== null && $token === $accessToken) {
  46.     //             return new Response($challenge);
  47.     //         } else {
  48.     //             return new Response(null, 400);
  49.     //         }
  50.     //     } catch (\Exception $e) {
  51.     //         return new Response(null, 400);
  52.         // }
  53.     
  54.     #[Route('/message/communication'name'app_message_communication'methods: ['GET''POST'])]
  55.     public function MessageCommunication(Request $requestSessionRepository $SessionRepositoryClientRepository $ClientRepositoryEntityManagerInterface $entityManager): Response
  56.     {
  57.         $json $request->getContent();
  58.         $data json_decode($jsontrue);
  59.         
  60.         $messages $data['entry'][0]['changes'][0]['value']['messages'][0];
  61.         $name $data['entry'][0]['changes'][0]['value']['contacts'][0]['profile']['name'];
  62.         // $userMessage = $data['entry'][0]['changes'][0]['value']['messages'][0]['text']['body'];
  63.         // $name = "djafara";
  64.         $number $messages['from'];
  65.         // $number = "22792829789";
  66.         $typeMessage $messages['type'];
  67.         // message texte
  68.         // $userMessage = $messages['text']['body'];
  69.         $client=$ClientRepository->findOneBy(['telephone' => $number'statut' => 1]);
  70.         if (!$client) {
  71.             //on cree le client
  72.             $client = new Client();
  73.             $client->setNomPrenom($name);
  74.             $client->setTelephone($number);
  75.             $client->setAdresse("");
  76.             $client->setCreatedAt(new DateTimeImmutable());
  77.             $client->setStatut(1);
  78.             $entityManager->persist($client);
  79.             $entityManager->flush();
  80.         }
  81.         
  82.         $session $SessionRepository->findOneBy(['idClient' => $client->getId(),'statut' => 1]);
  83.         if ($typeMessage=='text') {
  84.             if ($messages['text']['body']=="Merci" || $messages['text']['body']=="Au revoir")
  85.             {
  86.                 $session->setStatut(0);
  87.                 $session->setDeletedAt(new DateTimeImmutable());
  88.                 $entityManager->persist($session);
  89.                 $entityManager->flush();
  90.                 $this->envoyerSimpleMessage("*Session expirée*\n Merci d'avoir utilisé notre service. nous restons a votre disposition pour de futurs échanges \nA tres bientot."$number);
  91.             }
  92.             # code...
  93.         }
  94.         
  95.         if (!$session) {
  96.             // Con cree une nouvelle session
  97.             $session = new Session();
  98.             $session->setIdClient($client);
  99.             $session->setEtape(0);            //etape 0 creation de la session
  100.             $session->setTempsConnexion(0);
  101.             
  102.             $session->setCreatedAt(new DateTimeImmutable());
  103.             $session->setStatut(1);
  104.             $entityManager->persist($session);
  105.             $entityManager->flush();
  106.             $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.";
  107.             $this->MessageChoixService($text$number);
  108.         }
  109.         // if ($messages['text']['body']=="Merci" || $messages['text']['body']=="Au revoir")
  110.         // {
  111.         //     $session->setStatut(0);
  112.         //     $session->setDeletedAt(new DateTimeImmutable());
  113.         //     $entityManager->persist($session);
  114.         //     $entityManager->flush();
  115.         //     $this->envoyerSimpleMessage("*Session expirée*\n Merci d'avoir utilisé notre service. nous restons a votre disposition pour de futurs échanges \nA tres bientot.", $number);
  116.         // }
  117.         if ($session->getEtape()==0) {
  118.             $isInteractive = isset($messages['interactive']);
  119.             if (isset($messages['interactive'])) {
  120.                 
  121.                 // si l'utilisateur fait un choix
  122.                 $choix $messages['interactive']['list_reply']['id'];
  123.                 $session->setService($choix);
  124.                 $session->setEtape(1);           //etape 1 choix service
  125.                 $entityManager->persist($session);
  126.                 $entityManager->flush();
  127.                 switch ($choix) {
  128.                     case "Sc_001":
  129.                         // agro méteo
  130.                         // on enregistre dans la table recherche agro meteo
  131.                         $agrometeo = new RechercheAgroMeteo();
  132.                         $agrometeo->setIdSession($session);
  133.                         $agrometeo->setEtape(0);            //etape 0 creation
  134.                         
  135.                         $agrometeo->setCreatedAt(new DateTimeImmutable());
  136.                         $agrometeo->setStatut(1);
  137.                         $entityManager->persist($agrometeo);
  138.                         $entityManager->flush();
  139.                         // $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é.";
  140.                         $text "Veuillez choisir le type d'information souhaité.";
  141.                         $this->ChoixInformation($text,$number);
  142.                         break;
  143.                     case "Sc_002":
  144.                         
  145.                         $apuisconseil = new RechercheAppuisConseil();
  146.                         $apuisconseil->setIdSession($session);
  147.                         $apuisconseil->setEtape(0); // étape domaine
  148.                         $apuisconseil->setCreatedAt(new DateTimeImmutable());
  149.                         $apuisconseil->setStatut(1);
  150.                         $entityManager->persist($apuisconseil);
  151.                         $entityManager->flush();
  152.                         // On envoie la liste des domaines en interactive
  153.                         $this->ChoixDomaine($number);
  154.                         // Ne change pas encore $session->etape, on reste à 1 global
  155.                         break;
  156.                         // si appuis conseil
  157.                         // on enregistre dans la table recherche appuis conseil
  158.                         // $apuisconseil = new RechercheAppuisConseil();
  159.                         // $apuisconseil->setIdSession($session);
  160.                         // $apuisconseil->setEtape(0);            //etape 0 creation de l' apuisconseil
  161.                         
  162.                         // $apuisconseil->setCreatedAt(new DateTimeImmutable());
  163.                         // $apuisconseil->setStatut(1);
  164.                         // $entityManager->persist($apuisconseil);
  165.                         // $entityManager->flush();
  166.                         // // $text = "Très bien ! Vous avez choisi *APPuis*.\nVeuillez entrer la localité souhaitée.";
  167.                         // $this->ChoixDomaine($number);
  168.                         
  169.                         // break;
  170.                     case "Sc_003":
  171.                         // si prix
  172.                         // on enregistre dans la table rechercheprix
  173.                         $rechercheprix = new RecherchePrix();
  174.                         $rechercheprix->setIdSession($session);
  175.                         $rechercheprix->setEtape(0);            //etape 0 creation
  176.                         
  177.                         $rechercheprix->setCreatedAt(new DateTimeImmutable());
  178.                         $rechercheprix->setStatut(1);
  179.                         $entityManager->persist($rechercheprix);
  180.                         $entityManager->flush();
  181.                         $text "Veuillez choisir le type d'information souhaité.";
  182.                         $this->EnvoyerListeCategories($text,$number);
  183.                         break;
  184.                     default:
  185.                         $this->envoyerSimpleMessage("Désolé je n'ai pas reconnu ce choix."$number);
  186.                 }
  187.             } 
  188.             // else {
  189.             //      $this->envoyerSimpleMessage("Veuillez faire votre choix.", $number);
  190.             // }
  191.         }else {
  192.             $choix $session->getService();
  193.             switch ($choix) {
  194.                 case "Sc_001":
  195.                     // agro méteo
  196.                     $this->TraiterAgroMeteo($data,$session,$entityManager);
  197.                     break;
  198.                 case "Sc_002":
  199.                     // $apuisconseil = $entityManager->getRepository(RechercheAppuisConseil::class)->findOneBy(['idSession' => $session->getId(), 'statut' => 1]);
  200.                     // if ($apuisconseil && $session->getEtape()==2) {
  201.                         // si appuis conseil
  202.                         $this->TraiterAppuisConseil($data,$session,$entityManager);
  203.                         break;
  204.                     // }
  205.                 case "Sc_003":
  206.                     // si prix
  207.                     $this->TraiterPrix($data$session$entityManager);
  208.                     
  209.                     break;
  210.                 default:
  211.                     $this->envoyerSimpleMessage("Veuillez recommencer je n'ai pas reconnu ce choix."$number);
  212.             }
  213.         }
  214.     }
  215.     public function TraiterPrix($data$session$entityManager)
  216.     {
  217.         $messages $data['entry'][0]['changes'][0]['value']['messages'][0];
  218.         $number $messages['from'];
  219.         $typeMessage $messages['type'];
  220.         if ($typeMessage === "text") {
  221.             $texte trim($messages['text']['body']);
  222.             if ($texte === "Merci" || $texte === "Au revoir") {
  223.                 $session->setStatut(0);
  224.                 $session->setDeletedAt(new DateTimeImmutable());
  225.                 $entityManager->persist($session);
  226.                 $entityManager->flush();
  227.                 $this->envoyerSimpleMessage(
  228.                     "*Session expirée*\nMerci d'avoir utilisé notre service prix.\nÀ très bientôt.",
  229.                     $number
  230.                 );
  231.                 return;
  232.             }
  233.         }
  234.         $prixSession $entityManager->getRepository(RecherchePrix::class)
  235.             ->findOneBy(['idSession' => $session->getId(), 'statut' => 1]);
  236.         if (!$prixSession) {
  237.             $this->envoyerSimpleMessage("Aucune session."$number);
  238.                 return;
  239.             // $prixSession = new RecherchePrix();
  240.             // $prixSession->setIdSession($session);
  241.             // $prixSession->setEtape(0);            //etape 0 creation
  242.             
  243.             // $prixSession->setCreatedAt(new DateTimeImmutable());
  244.             // $prixSession->setStatut(1);
  245.             // $entityManager->persist($prixSession);
  246.             // $entityManager->flush();
  247.             // $this->EnvoyerListeCategories("Veuillez choisir une catégorie :", $number);
  248.             // return;
  249.         }
  250.         /*  ÉTAPE 0 : CHOIX CATÉGORIE  */
  251.         if ($prixSession->getEtape() == 0) {
  252.             if (isset($messages['interactive']['list_reply']['id'])) {
  253.                 $choix $messages['interactive']['list_reply']['id'];
  254.                 if ($choix === "Pc_001") {
  255.                     $prixSession->setType("AGRICULTURE");
  256.                     $prixSession->setEtape(1);
  257.                     $entityManager->flush();
  258.                     $this->envoyerSimpleMessage(
  259.                         "Vous avez choisi *AGRO ALIMENTAIRE*.\n\nVeuillez saisir le nom d'une commune :",
  260.                         $number
  261.                     );
  262.                     return;
  263.                 }
  264.                 if ($choix === "Pc_002") {
  265.                     $prixSession->setType("BETAIL");
  266.                     $prixSession->setEtape(1);
  267.                     $entityManager->flush();
  268.                     $this->envoyerSimpleMessage(
  269.                         "Vous avez choisi *ANIMAUX / BÉTAIL*.\n\nVeuillez saisir le nom d'une commune :",
  270.                         $number
  271.                     );
  272.                     return;
  273.                 }
  274.                 $this->envoyerSimpleMessage("Choix invalide, veuillez réessayer."$number);
  275.                 return;
  276.             }
  277.             // Si aucun choix reçu, envoyer la liste de catégories
  278.             $this->EnvoyerListeCategories("Veuillez choisir une catégorie :"$number);
  279.             return;
  280.         }
  281.         /* ÉTAPE 1 : RECHERCHE DE COMMUNE */
  282.         if ($prixSession->getEtape() == ) {
  283.             if ($typeMessage !== "text") {
  284.                 $this->envoyerSimpleMessage(
  285.                     "Veuillez saisir un nom de commune sous forme de texte.",
  286.                     $number
  287.                 );
  288.                 return;
  289.             }
  290.             $texteRecu trim($messages['text']['body']);
  291.             $listeCommunes $this->AppelApiRechercheCommunes($texteRecu);
  292.             if (empty($listeCommunes)) {
  293.                 $this->envoyerSimpleMessage(
  294.                     "Aucune commune trouvée pour *$texteRecu*.\nVeuillez saisir un autre nom.",
  295.                     $number
  296.                 );
  297.                 return;
  298.             }
  299.             // Stocker la liste pour sélection
  300.             $prixSession->setListeResultat(json_encode($listeCommunes));
  301.             $prixSession->setEtape(2);
  302.             $entityManager->flush();
  303.             $this->EnvoyerListeCommunes($listeCommunes$number);
  304.             return;
  305.         }
  306.         /*  ÉTAPE 2 : CHOIX D'UNE COMMUNE */
  307.         if ($prixSession->getEtape() == && $typeMessage === "text") {
  308.             $choix trim($messages['text']['body']);
  309.             if (!ctype_digit($choix)) {
  310.                 $this->envoyerSimpleMessage("Veuillez saisir un numéro valide."$number);
  311.                 return;
  312.             }
  313.             $listeCommunes json_decode($prixSession->getListeResultat(), true);
  314.             $index intval($choix) - 1;
  315.             if (!isset($listeCommunes[$index])) {
  316.                 $this->envoyerSimpleMessage("Numéro invalide. Veuillez réessayer."$number);
  317.                 return;
  318.             }
  319.             $commune $listeCommunes[$index];
  320.             $prixSession->setCommune($commune['id']);
  321.             $prixSession->setListeResultat(null);
  322.             $prixSession->setEtape(3);
  323.             $entityManager->flush();
  324.             /* les prix selon la catégorie */
  325.             if ($prixSession->getType() === "AGRICULTURE") {
  326.                 $listePrix $this->AppelApiPrixProduitsAgricoles($commune['id']);
  327.                 $this->EnvoyerPrixProduitsAgricoles($listePrix$number);
  328.                 $prixSession->setStatut(0);
  329.                 $prixSession->setDeletedAt(new DateTimeImmutable());
  330.                 $session->setStatut(0);
  331.                 $session->setDeletedAt(new DateTimeImmutable());
  332.                 $entityManager->persist($session);
  333.                 $entityManager->flush();
  334.                 $this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !"$number);
  335.                 return;
  336.             }
  337.             if ($prixSession->getType() === "BETAIL") {
  338.                 $listePrix $this->AppelApiPrixBetail($commune['id']);
  339.                 $this->EnvoyerPrixBetail($listePrix$number);
  340.                 $prixSession->setStatut(0);
  341.                 $prixSession->setDeletedAt(new DateTimeImmutable());
  342.                 $session->setStatut(0);
  343.                 $session->setDeletedAt(new DateTimeImmutable());
  344.                 $entityManager->persist($session);
  345.                 $entityManager->flush();
  346.                 $this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !"$number);
  347.                 return;
  348.             }
  349.             return;
  350.         }
  351.         /* ERREUR PAR DÉFAUT  */
  352.         $this->envoyerSimpleMessage("Désolé, je n'ai pas reconnu votre choix."$number);
  353.     }
  354.     
  355.     public function EnvoyerListeCommunes(array $listeCommunesstring $number)
  356.     {
  357.         if (empty($listeCommunes)) {
  358.             $this->envoyerSimpleMessage("Aucune commune trouvée. Veuillez réessayer."$number);
  359.             return;
  360.         }
  361.         $message "*Communes trouvées :*\n\n";
  362.         $i 1;
  363.         foreach ($listeCommunes as $commune) {
  364.             $message .= "👉 Tapez *".$i."* pour *".$commune['libelle']."*\n";
  365.             $i++;
  366.         }
  367.         $message .= "\n*Tapez le numéro* correspondant à votre commune.";
  368.         // CORRECTION : utiliser $number et NON $numero
  369.         $this->envoyerSimpleMessage($message$number);
  370.     }
  371.     public function AppelApiRechercheCommunes(string $texte): array 
  372.     {  
  373.         //Authentification API 
  374.         $auth $this->fonct->execPost('''api/authentification'json_encode([
  375.             "email" => "djafarasakinatou@gmail.com",
  376.             "password" => "l2323"
  377.         ]));
  378.           
  379.         //Appel API de recherche des communes 
  380.         $response $this->fonct->execPost$auth['data']['token'], 'api/communes/recherche'json_encode([ "commune" => $texte ]) );  
  381.        
  382.         //Vérification réponse 
  383.         if (!isset($response['status']) || $response['status'] != 200
  384.         { 
  385.             return []; 
  386.         }  
  387.         //Retourne la liste des résultats 
  388.         return $response['results'] ?? []; 
  389.     }
  390.     public function AppelApiPrixBetail(string $idCommune): array 
  391.     { 
  392.         // Authentification API 
  393.         $auth $this->fonct->execPost('''api/authentification'json_encode([
  394.             "email" => "djafarasakinatou@gmail.com",
  395.             "password" => "l2323"
  396.         ]));
  397.         // Appel API Prix Bétail 
  398.         $response $this->fonct->execPost$auth['data']['token'], 'api/prix/animaux'json_encode([ "id_commune" => $idCommune ]) ); 
  399.         if (!isset($response['status']) || $response['status'] != 200
  400.         { 
  401.             return []; 
  402.         } 
  403.         return $response['data'] ?? []; 
  404.     }
  405.     public function AppelApiPrixProduitsAgricoles(string $idCommune): array
  406.     {
  407.         // Authentification API
  408.         $auth $this->fonct->execPost('''api/authentification'json_encode([
  409.             "email" => "djafarasakinatou@gmail.com",
  410.             "password" => "l2323"
  411.         ]));
  412.         // Appel API Prix Produits Agricoles
  413.         $response $this->fonct->execPost(
  414.             $auth['data']['token'],
  415.             'api/prix/produit/agricole',
  416.             json_encode([
  417.                 "id_commune" => $idCommune,
  418.                 "id_semaine" => "" // ton API prend automatiquement la semaine active
  419.             ])
  420.         );
  421.         // Vérification du status
  422.         if (!isset($response['status']) || $response['status'] != 200) {
  423.             return [];
  424.         }
  425.         // Retour des données
  426.         return $response['data'] ?? [];
  427.     }
  428.     public function EnvoyerListeCategories(string $textstring $number
  429.     { 
  430.         $apiUrl 'https://graph.facebook.com/v22.0/870067449513702/messages';
  431.         $token 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
  432.         
  433.         $payload = [ 
  434.             "messaging_product" => "whatsapp"
  435.             "to" => $number
  436.             "type" => "interactive"
  437.             "interactive" => [ 
  438.                 "type" => "list",
  439.                 "body" => [ 
  440.                     "text" => $text 
  441.                 ], 
  442.                 "footer" => [ 
  443.                     "text" => "Pour arrêter le processus tapez merci ou au revoir" 
  444.                 ], 
  445.                 "action" => [ 
  446.                     "button" => "Catégories"
  447.                     "sections" => [ 
  448.                         [ 
  449.                             "title" => "Catégories disponibles"
  450.                             "rows" => [ 
  451.                                 [ 
  452.                                     "id" => "Pc_001"
  453.                                     "title" => "AGRO ALIMENT"
  454.                                     "description" => "Prix des aliments d'une localité du Niger" 
  455.                                 ],
  456.                                 [ 
  457.                                     "id" => "Pc_002"
  458.                                     "title" => "ANIMAUX"
  459.                                     "description" => "Prix du bétail d'une localité du Niger" 
  460.                                 
  461.                             ] 
  462.                         ] 
  463.                     ] 
  464.                 ] 
  465.             ] 
  466.         ]; 
  467.         try { 
  468.             $response $this->client->request('POST'$apiUrl, [ 
  469.                 'headers' => [ 
  470.                     'Authorization' => 'Bearer ' $token
  471.                     'Content-Type' => 'application/json'
  472.                 ], 
  473.                 'json' => $payload
  474.             ]); 
  475.             $result $response->toArray(false); 
  476.             return $result;
  477.         } catch (\Exception $e) {
  478.             return ['error' => $e->getMessage()];
  479.         }
  480.     }
  481.     public function EnvoyerPrixBetail(array $prixstring $number)
  482.     {
  483.         $apiUrl 'https://graph.facebook.com/v22.0/870067449513702/messages';
  484.         $token 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
  485.         // Construction du message
  486.         if (empty($prix)) {
  487.             $texte " *Aucun prix de bétail trouvé pour cette commune.*";
  488.         } else {
  489.             $texte " *Prix du Bétail*\n\n";
  490.             foreach ($prix as $item) {
  491.                 $texte .= " *" $item["animal"] . "*\n";
  492.                 $texte .= " Prix : " $item["prix"] . " FCFA\n";
  493.                 $texte .= "-------------------------\n";
  494.             }
  495.         }
  496.         $payload = [
  497.             "messaging_product" => "whatsapp",
  498.             "to" => $number,
  499.             "type" => "text",
  500.             "text" => [
  501.                 "body" => $texte
  502.             ]
  503.         ];
  504.         try {
  505.             $response $this->client->request('POST'$apiUrl, [
  506.                 'headers' => [
  507.                     'Authorization' => 'Bearer ' $token,
  508.                     'Content-Type' => 'application/json',
  509.                 ],
  510.                 'json' => $payload,
  511.             ]);
  512.             return $response->toArray();
  513.         } catch (\Exception $e) {
  514.             return ['error' => $e->getMessage()];
  515.         }
  516.     }
  517.     
  518.     public function EnvoyerPrixProduitsAgricoles(array $prixstring $number
  519.     { 
  520.         $apiUrl 'https://graph.facebook.com/v22.0/870067449513702/messages'
  521.         $token 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD'
  522.         // Construction du message 
  523.         if (empty($prix)) 
  524.         { 
  525.             $texte " *Aucun prix de produit agricole trouvé pour cette commune.*"
  526.         } else 
  527.         { 
  528.             $texte " *Prix des produits agricoles*\n\n"
  529.             foreach ($prix as $item
  530.             { 
  531.                 $texte .= " *" $item["produit"] . "*\n"
  532.                 $texte .= " Prix : " $item["prix"] . " FCFA\n"
  533.                 $texte .= "-------------------------\n"
  534.             } 
  535.         } 
  536.         $payload = [ 
  537.             "messaging_product" => "whatsapp"
  538.             "to" => $number
  539.             "type" => "text"
  540.             "text" => [ 
  541.                 "body" => $texte 
  542.             
  543.         ]; 
  544.         try 
  545.         {
  546.             $response $this->client->request('POST'$apiUrl, [ 'headers' => [ 'Authorization' => 'Bearer ' $token'Content-Type' => 'application/json', ], 'json' => $payload, ]); 
  547.             return $response->toArray(); 
  548.         } catch (\Exception $e
  549.         { 
  550.             return ['error' => $e->getMessage()]; 
  551.         } 
  552.     }
  553.     public function TraiterAgroMeteo($data,$session,$entityManager)
  554.     {
  555.         $messages $data['entry'][0]['changes'][0]['value']['messages'][0];
  556.         $number $messages['from'];
  557.         $typeMessage $messages['type'];
  558.         if ($typeMessage === "text") {
  559.             $texte trim($messages['text']['body']);
  560.             if ($texte === "Merci" || $texte === "Au revoir") {
  561.                 $session->setStatut(0);
  562.                 $session->setDeletedAt(new DateTimeImmutable());
  563.                 $entityManager->persist($session);
  564.                 $entityManager->flush();
  565.                 $this->envoyerSimpleMessage(
  566.                     "*Session expirée*\nMerci d'avoir utilisé notre service prix.\nÀ très bientôt.",
  567.                     $number
  568.                 );
  569.                 return;
  570.             }
  571.         }
  572.         $agrometeo $entityManager->getRepository(RechercheAgroMeteo::class)->findOneBy(['idSession' => $session->getId(),'statut' => 1]);
  573.         
  574.         
  575.            // Fin de session
  576.         // if ($agrometeo->getEtape()==3)
  577.         // {
  578.         //     $session->setStatut(0);
  579.         //     $session->setDeletedAt(new DateTimeImmutable());
  580.         //     $entityManager->flush();
  581.         //     $this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !", $number);
  582.         //     return;
  583.         // }
  584.         
  585.         if (!$agrometeo) {
  586.             $this->envoyerSimpleMessage("Aucune session."$number);
  587.                 return;
  588.             // $agrometeo = new RechercheAgroMeteo();
  589.             // $agrometeo->setIdSession($session);
  590.             // $agrometeo->setEtape(0);            //etape 0 creation
  591.             
  592.             // $agrometeo->setCreatedAt(new DateTimeImmutable());
  593.             // $agrometeo->setStatut(1);
  594.             // $entityManager->persist($agrometeo);
  595.             // $entityManager->flush();
  596.             // // $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é.";
  597.             // $text = "Veuillez choisir le type d'information souhaité.";
  598.             // $this->ChoixInformation($text,$number);
  599.             // return;
  600.         }
  601.         if ($agrometeo->getEtape()==0) {
  602.             if (isset($messages['interactive']['list_reply']['id'])) {
  603.                 $choix $messages['interactive']['list_reply']['id'];
  604.             } else {
  605.                 $this->envoyerSimpleMessage("Veuillez sélectionner un type d'information dans la liste."$number);
  606.                 return;
  607.             }
  608.             
  609.             $agrometeo->setType($choix);
  610.             $agrometeo->setEtape(1); // choix type info
  611.             $entityManager->persist($agrometeo);
  612.             $entityManager->flush();
  613.             
  614.             
  615.             // $text = "Veuillez saissir la localité souhaitée.";
  616.             // $this->envoyerSimpleMessage($text, $number);
  617.             
  618.         }
  619.         if ($agrometeo->getEtape()==&& $agrometeo->getType()!=null) {// si etape 1 choix commune fait
  620.             if ($typeMessage !== "text") {
  621.                 $this->envoyerSimpleMessage("Veuillez saisir un nom de commune sous forme de texte.",$number);
  622.                 return;
  623.             }
  624.             $texteRecu trim($messages['text']['body']);
  625.             $listeCommunes $this->AppelApiRechercheCommunes($texteRecu);
  626.                 if (empty($listeCommunes)) {
  627.                     $this->envoyerSimpleMessage(
  628.                         "Aucune commune trouvée pour *$texteRecu*.\nVeuillez saisir un autre nom.",
  629.                         $number
  630.                     );
  631.                     return;
  632.                 }
  633.                 $agrometeo->setResultat(json_encode($listeCommunes));
  634.                 $agrometeo->setEtape(2); //saissi commune
  635.                 $entityManager->persist($agrometeo);
  636.                 $entityManager->flush();
  637.             $this->EnvoyerListeCommunes($listeCommunes$number);
  638.             return;
  639.         }
  640.         if ($agrometeo->getEtape() == 2) {
  641.             // $this->envoyerSimpleMessage("ok", $number);
  642.             $userMessage trim($messages['text']['body']);
  643.             if ($typeMessage !== "text") {
  644.                 $this->envoyerSimpleMessage("Veuillez saisir un numéro."$number);
  645.                 return;
  646.             }
  647.             if (!ctype_digit($messages['text']['body'])) {
  648.                 $this->envoyerSimpleMessage("Numéro invalide."$number);
  649.                 return;
  650.             }
  651.             $listeCommunes json_decode($agrometeo->getResultat(), true);
  652.             $index intval($messages['text']['body']) - 1;
  653.             if (!isset($listeCommunes[$index])) {
  654.                 $this->envoyerSimpleMessage("Numéro invalide. Veuillez réessayer."$number);
  655.                 return;
  656.             }
  657.             $commune $listeCommunes[$index];
  658.             $idCommune=$commune['id'];
  659.             // Enregistrer dans la base
  660.             $agrometeo->setCommune($idCommune);
  661.             $agrometeo->setEtape(3);
  662.             $entityManager->flush();
  663.             // Continue selon type
  664.             if ($agrometeo->getType() == "In_01") {
  665.                 
  666.                 $this->EnvoyerDateSemis($idCommune$number);
  667.                 $agrometeo->setStatut(0);
  668.                 $agrometeo->setDeletedAt(new DateTimeImmutable());
  669.                 $session->setStatut(0);
  670.                 $session->setDeletedAt(new DateTimeImmutable());
  671.                 $entityManager->persist($session);
  672.                 $entityManager->flush();
  673.                 $this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !"$number);
  674.                 return;
  675.             }
  676.             if ($agrometeo->getType() == "In_02") {
  677.                 
  678.                 $this->EnvoyerPocheSecheresse($idCommune$number);
  679.                 $agrometeo->setStatut(0);
  680.                 $agrometeo->setDeletedAt(new DateTimeImmutable());
  681.                 $session->setStatut(0);
  682.                 $session->setDeletedAt(new DateTimeImmutable());
  683.                 $entityManager->persist($session);
  684.                 $entityManager->flush();
  685.                 $this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !"$number);
  686.                 return;
  687.             }
  688.             if ($agrometeo->getType() == "In_03") {
  689.                 
  690.                 $this->EnvoyerDateSaison($idCommune$number);
  691.                 $agrometeo->setStatut(0);
  692.                 $agrometeo->setDeletedAt(new DateTimeImmutable());
  693.                 $session->setStatut(0);
  694.                 $session->setDeletedAt(new DateTimeImmutable());
  695.                 $entityManager->persist($session);
  696.                 $entityManager->flush();
  697.                 $this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !"$number);
  698.                 return;
  699.             }
  700.             if ($agrometeo->getType() == "In_04") {
  701.                 
  702.                 $this->EnvoyerAlerte($idCommune$number);
  703.                 $agrometeo->setStatut(0);
  704.                 $agrometeo->setDeletedAt(new DateTimeImmutable());
  705.                 $session->setStatut(0);
  706.                 $session->setDeletedAt(new DateTimeImmutable());
  707.                 $entityManager->persist($session);
  708.                 $entityManager->flush();
  709.                 $this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !"$number);
  710.                 return;
  711.             }
  712.             return;
  713.         }
  714.     
  715.     }
  716.     public function EnvoyerDateSemis($idCommune$number)
  717.     {   
  718.         // Authentification
  719.         $auth $this->fonct->execPost('''api/authentification'json_encode(["email"=> "djafarasakinatou@gmail.com","password"=> "l2323"]));
  720.         //thématiques
  721.         $responsesemis $this->fonct->execPost($auth['data']['token'],'api/date/semis',json_encode(["id_commune" => $idCommune]));
  722.             // $this->envoyerSimpleMessage("ok", $number);
  723.         if (!isset($responsesemis['data'])) {
  724.             $this->envoyerSimpleMessage("Aucune donnée trouvée ."$number);
  725.             return;
  726.         }
  727.         $msg "Information disponible:\n";
  728.         foreach ($responsesemis['data'] as $semis) {
  729.             $msg .= "*{$semis['information']}*\n\n";
  730.         }
  731.         $msg .= "\nPour arrêter tapez *merci* ou *au revoir*.";
  732.         // Envoyer
  733.         $this->envoyerSimpleMessage($msg$number);
  734.     }
  735.     public function EnvoyerPocheSecheresse($idCommune$number)
  736.     {   
  737.         
  738.         // Authentification
  739.         $auth $this->fonct->execPost('''api/authentification'json_encode(["email"=> "djafarasakinatou@gmail.com","password"=> "l2323"]));
  740.         //thématiques
  741.         $responsesemis $this->fonct->execPost($auth['data']['token'],'api/poche/secheresse',json_encode(["id_commune" => $idCommune]));
  742.             // $this->envoyerSimpleMessage("ok", $number);
  743.         // 🔍 DEBUG : voir ce que retourne l'API
  744.         //$this->envoyerSimpleMessage("DEBUG : \n" . json_encode($responsesemis), $number);
  745.         if (!isset($responsesemis['data'])) {
  746.             $this->envoyerSimpleMessage("Aucune donnée trouvée ."$number);
  747.             return;
  748.         }
  749.         $msg "Information disponible:\n";
  750.         foreach ($responsesemis['data'] as $semis) {
  751.             $msg .= "*{$semis['information']}*\n\n";
  752.         }
  753.         $msg .= "\nPour arrêter tapez *merci* ou *au revoir*.";
  754.         // Envoyer
  755.         $this->envoyerSimpleMessage($msg$number);
  756.     }
  757.        public function EnvoyerDateSaison($idCommune$number)
  758.     {   
  759.         // Authentification
  760.         $auth $this->fonct->execPost('''api/authentification'json_encode(["email"=> "djafarasakinatou@gmail.com","password"=> "l2323"]));
  761.         //thématiques
  762.         $responsesemis $this->fonct->execPost($auth['data']['token'],'api/date/saison',json_encode(["id_commune" => $idCommune]));
  763.             // $this->envoyerSimpleMessage("ok", $number);
  764.         if (!isset($responsesemis['data'])) {
  765.             $this->envoyerSimpleMessage("Aucune donnée trouvée ."$number);
  766.             return;
  767.         }
  768.         $msg "Information disponible:\n";
  769.         foreach ($responsesemis['data'] as $semis) {
  770.             $msg .= "*{$semis['information']}*\n\n";
  771.         }
  772.         $msg .= "\nPour arrêter tapez *merci* ou *au revoir*.";
  773.         // Envoyer
  774.         $this->envoyerSimpleMessage($msg$number);
  775.     }
  776.     public function EnvoyerAlerte($idCommune$number)
  777.     {   
  778.         // Authentification
  779.         $auth $this->fonct->execPost('''api/authentification'json_encode(["email"=> "djafarasakinatou@gmail.com","password"=> "l2323"]));
  780.         //thématiques
  781.         $responsesemis $this->fonct->execPost($auth['data']['token'],'api/alerte',json_encode(["id_commune" => $idCommune]));
  782.             // $this->envoyerSimpleMessage("ok", $number);
  783.         if (!isset($responsesemis['data'])) {
  784.             $this->envoyerSimpleMessage("Aucune donnée trouvée ."$number);
  785.             return;
  786.         }
  787.         $msg "Information disponible:\n";
  788.         foreach ($responsesemis['data'] as $semis) {
  789.             $msg .= "*{$semis['information']}*\n\n";
  790.         }
  791.         $msg .= "\nPour arrêter tapez *merci* ou *au revoir*.";
  792.         // Envoyer
  793.         $this->envoyerSimpleMessage($msg$number);
  794.     }
  795.     public function TraiterAppuisConseil($data$session$entityManager)
  796.     {
  797.         $messages $data['entry'][0]['changes'][0]['value']['messages'][0];
  798.         $number $messages['from'];
  799.         $typeMessage $messages['type'];
  800.         if ($typeMessage === "text") {
  801.             $texte trim($messages['text']['body']);
  802.             if ($texte === "Merci" || $texte === "Au revoir") {
  803.                 $session->setStatut(0);
  804.                 $session->setDeletedAt(new DateTimeImmutable());
  805.                 $entityManager->persist($session);
  806.                 $entityManager->flush();
  807.                 $this->envoyerSimpleMessage(
  808.                     "*Session expirée*\nMerci d'avoir utilisé notre service prix.\nÀ très bientôt.",
  809.                     $number
  810.                 );
  811.                 return;
  812.             }
  813.         }
  814.         $apuisconseil $entityManager->getRepository(RechercheAppuisConseil::class)->findOneBy(['idSession' => $session->getId(), 'statut' => 1]);
  815.         if (!$apuisconseil) {
  816.             $this->envoyerSimpleMessage("Aucune session."$number);
  817.                 return;
  818.             // $apuisconseil = new RechercheAppuisConseil();
  819.             // $apuisconseil->setIdSession($session);
  820.             // $apuisconseil->setEtape(0); // étape domaine
  821.             // $apuisconseil->setCreatedAt(new DateTimeImmutable());
  822.             // $apuisconseil->setStatut(1);
  823.             // $entityManager->persist($apuisconseil);
  824.             // $entityManager->flush();
  825.             // // On envoie la liste des domaines en interactive
  826.             // $this->ChoixDomaine($number);
  827.             // return;
  828.         }
  829.         if ($apuisconseil->getEtape() == 0) {
  830.             // $this->envoyerSimpleMessage("❌ Session Appuis Conseil introuvable.", $number);
  831.             // return;
  832.             // Récupère le choix domaine depuis interactive ou texte
  833.             
  834.             if (isset($messages['interactive']['list_reply']['id'])) {
  835.                 $choix $messages['interactive']['list_reply']['id'];
  836.             } else {
  837.                 $this->envoyerSimpleMessage("Veuillez sélectionner un type d'information dans la liste."$number);
  838.                 return;
  839.             }
  840.             $theme $this->thematiqueTrouver($choix);
  841.                 if (empty($theme)) {
  842.                     $this->envoyerSimpleMessage(
  843.                         "Aucun thème trouvé.",
  844.                         $number
  845.                     );
  846.                     return;
  847.                 }
  848.             $apuisconseil->setResultat(json_encode($theme));
  849.             $apuisconseil->setDomaine($choix);
  850.             $apuisconseil->setEtape(1); // étape thématique
  851.             $entityManager->flush();
  852.             $this->EnvoyerListeThematique($choix$number);
  853.             return;
  854.         }
  855.         if ($apuisconseil->getEtape() == && $typeMessage == "text") {
  856.             
  857.             
  858.             $choixThematique trim($messages['text']['body']);
  859.            
  860.             // Vérifie que le choix est un ID numérique ou valide
  861.             if (!ctype_digit($choixThematique)) {
  862.                 $this->envoyerSimpleMessage("Veuillez saisir un numéro valide."$number);
  863.                 return;
  864.             }
  865.             
  866.             $listetheme json_decode($apuisconseil->getResultat(), true);
  867.             $index intval($choixThematique) - 1;
  868.             if (!isset($listetheme[$index])) {
  869.                 $this->envoyerSimpleMessage("Numéro invalide. Veuillez réessayer."$number);
  870.                 return;
  871.             }
  872.             $theme $listetheme[$index];
  873.             $idTheme=$theme['id'];
  874.             $apuisconseil->setThematique($idTheme);
  875.             $apuisconseil->setEtape(2); // fin
  876.             $entityManager->flush();
  877.             
  878.             $this->envoyerFichierTheme($number$idTheme);
  879.             $apuisconseil->setStatut(0);
  880.             $apuisconseil->setDeletedAt(new DateTimeImmutable());
  881.             $session->setStatut(0);
  882.             $session->setDeletedAt(new DateTimeImmutable());
  883.             $entityManager->flush();
  884.             $this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !"$number);
  885.             return;
  886.         }
  887.     }
  888.     #[Route('/communication'name'app_communication'methods: ['GET''POST'])]
  889.     public function index(Request $requestMessageRepository $messageRepository): Response
  890.     {
  891.         $message = new Message();
  892.         $form $this->createForm(MessageType::class, $message);
  893.         $form->handleRequest($request);  
  894.         if ($form->isSubmitted() && $form->isValid()) {
  895.             $imageFiles $form->get('image')->getData();
  896.             $telephone $form->get('telephone')->getData();
  897.             $contenus $form->get('contenus')->getData();
  898.             $titre $form->get('titre')->getData();
  899.             if ($imageFiles) {
  900.                 foreach ($imageFiles as $imageFile) {
  901.                     $newFilename uniqid().'.'.$imageFile->guessExtension();
  902.                     try {
  903.                         $imageFile->move(
  904.                             $this->getParameter('messages_images_directory'),
  905.                             $newFilename
  906.                         );
  907.                     } catch (FileException $e) {
  908.                         $this->addFlash('error''Impossible de télécharger une image.');
  909.                         continue;
  910.                     }
  911.                     $message->addImage($newFilename);
  912.                 }
  913.             }
  914.             $message->setCreatedAt(new \DateTimeImmutable());
  915.             $message->setStatus(1);
  916.             $message->setIdUser($this->getUser());
  917.             $messageRepository->add($messagetrue);
  918.             
  919.             $resultat $this->envoyerMessage("227"$telephone$titre,  $contenus);
  920.             if ($imageFiles) {
  921.             $resultat $this->envoyerMessagePlusDocument("227"$telephone"1" );
  922.             }
  923.             return $this->redirectToRoute('app_communication', [], Response::HTTP_SEE_OTHER);
  924.         }
  925.         $messages $messageRepository->findBy(
  926.             ['status' => 1],
  927.             ['createdAt' => 'DESC']
  928.         );
  929.         
  930.         $this->addFlash('success''Message envoyé avec succès !');    
  931.         return $this->render('message/index.html.twig', [
  932.             'messages' => $messages,
  933.             'form' => $form->createView(),
  934.         ]);
  935.     }
  936.     #[Route('/message/{id}'name'app_message_show'methods: ['GET''POST'])]
  937.     public function show(Message $messageMessageRepository $messageRepository): Response
  938.     {
  939.         
  940.         return $this->render('message/detail.html.twig', [
  941.             
  942.             'messages' => $messageRepository->findBy(
  943.             ['status' => 1],
  944.             ['createdAt' => 'DESC']
  945.         ),
  946.             'message' => $message,
  947.         ]);
  948.     }
  949.     public function envoyerSimpleMessage(string $contenus,string $numero)
  950.     {
  951.         $apiUrl 'https://graph.facebook.com/v22.0/870067449513702/messages';
  952.         $token =  'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
  953.         
  954.         $data = [
  955.             "messaging_product" => "whatsapp",
  956.             "recipient_type" => "individual",
  957.             "to" => "$numero"// numéro du destinataire
  958.             "type" => "text",
  959.             "text" => [
  960.                 "preview_url" => false,
  961.                 "body" => $contenus
  962.             ]
  963.         ];
  964.         $ch curl_init();
  965.         curl_setopt_array($ch, [
  966.             CURLOPT_URL => $apiUrl,
  967.             CURLOPT_RETURNTRANSFER => true,
  968.             CURLOPT_POST => true,
  969.             CURLOPT_HTTPHEADER => [
  970.                 "Authorization: Bearer $token",
  971.                 "Content-Type: application/json"
  972.             ],
  973.             CURLOPT_POSTFIELDS => json_encode($data)
  974.         ]);
  975.         $response curl_exec($ch);
  976.         curl_close($ch);
  977.     }
  978.     public function ChoixInformation(string $textstring $number)
  979.     {
  980.         $apiUrl 'https://graph.facebook.com/v22.0/870067449513702/messages';
  981.         $token 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
  982.         $payload = [
  983.             "messaging_product" => "whatsapp",
  984.             "to" => $number,
  985.             "type" => "interactive",
  986.             "interactive" => [
  987.                 "type" => "list",
  988.                 "body" => [
  989.                     "text" => $text
  990.                 ],
  991.                 "footer" => [
  992.                     "text" => "Pour arrêter le processus tapez merci ou au revoir"
  993.                 ],
  994.                 "action" => [
  995.                     "button" => "Choisir un type",
  996.                     "sections" => [
  997.                         [
  998.                             "title" => "Type information",
  999.                             "rows" => [
  1000.                                 [
  1001.                                     "id" => "In_01",
  1002.                                     "title" => "SEMIS",
  1003.                                     "description" => "Dates de semis"
  1004.                                 ],
  1005.                                 [
  1006.                                     "id" => "In_02",
  1007.                                     "title" => "SECHERESSE",
  1008.                                     "description" => "Poches de sècheresse"
  1009.                                 ],
  1010.                                 [
  1011.                                     "id" => "In_03",
  1012.                                     "title" => "SAISON",
  1013.                                     "description" => "Début et fin de la saison"
  1014.                                 ],
  1015.                                 [
  1016.                                     "id" => "In_04",
  1017.                                     "title" => "ALERTE",
  1018.                                     "description" => "Alerte sur l’invasion acridienne et aviaire"
  1019.                                 ]
  1020.                             ]
  1021.                         ]
  1022.                     ]
  1023.                 ]
  1024.             ]
  1025.         ];
  1026.         try {
  1027.             $response $this->client->request('POST'$apiUrl, [
  1028.                 'headers' => [
  1029.                     'Authorization' => 'Bearer ' $token,
  1030.                     'Content-Type' => 'application/json',
  1031.                 ],
  1032.                 'json' => $payload,
  1033.             ]);
  1034.             return $response->toArray();
  1035.         } catch (\Exception $e) {
  1036.             return ['error' => $e->getMessage()];
  1037.         }
  1038.     }
  1039.     public function MessageChoixService(string $textstring $number)
  1040.     {
  1041.         $apiUrl 'https://graph.facebook.com/v22.0/870067449513702/messages';
  1042.         $token 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
  1043.         $payload = [
  1044.             "messaging_product" => "whatsapp",
  1045.             "to" => $number,
  1046.             "type" => "interactive",
  1047.             "interactive" => [
  1048.                 "type" => "list",
  1049.                 "body" => [
  1050.                     "text" => $text
  1051.                 ],
  1052.                 "footer" => [
  1053.                     "text" => "Pour arrêter le processus tapez merci ou au revoir"
  1054.                 ],
  1055.                 "action" => [
  1056.                     "button" => "Choisir un service",
  1057.                     "sections" => [
  1058.                         [
  1059.                             "title" => "Services disponibles",
  1060.                             "rows" => [
  1061.                                 [
  1062.                                     "id" => "Sc_001",
  1063.                                     "title" => "AGRO METEO",
  1064.                                     "description" => "Prévisions météorologiques d'une localité du Niger"
  1065.                                 ],
  1066.                                 [
  1067.                                     "id" => "Sc_002",
  1068.                                     "title" => "APPUIS CONSEIL",
  1069.                                     "description" => "Conseils et assistance dans divers domaines"
  1070.                                 ],
  1071.                                 [
  1072.                                     "id" => "Sc_003",
  1073.                                     "title" => "PRIX",
  1074.                                     "description" => "Prix des animaux et produits agricoles dans les marchés du Niger"
  1075.                                 ]
  1076.                             ]
  1077.                         ]
  1078.                     ]
  1079.                 ]
  1080.             ]
  1081.         ];
  1082.         try {
  1083.             $response $this->client->request('POST'$apiUrl, [
  1084.                 'headers' => [
  1085.                     'Authorization' => 'Bearer ' $token,
  1086.                     'Content-Type' => 'application/json',
  1087.                 ],
  1088.                 'json' => $payload,
  1089.             ]);
  1090.             return $response->toArray();
  1091.         } catch (\Exception $e) {
  1092.             return ['error' => $e->getMessage()];
  1093.         }
  1094.     }
  1095.     public function ChoixDomaine(string $number)
  1096.     {
  1097.         
  1098.        //on recupere la connection
  1099.         $all=[
  1100.             "email"=> "djafarasakinatou@gmail.com",
  1101.             "password"=> "l2323"
  1102.         ];
  1103.         $dataPost=json_encode($all);
  1104.         $chemin='api/authentification';
  1105.         $response=$this->fonct->execPost('',$chemin,$dataPost);
  1106.        
  1107.         //on recupere les domaines
  1108.         $cheminDomaine='api/appuis/conseil/domaine';
  1109.         $responseDomaine=$this->fonct->execGet($response['data']['token'],$cheminDomaine);
  1110.         
  1111.         $messageListe = array();
  1112.         $text="Veuillez choisir un domaine";
  1113.         foreach ($responseDomaine['data'] as $domaine) {
  1114.             
  1115.             $messageListe[] = [
  1116.                             "id" => $domaine['id'],
  1117.                             "title" => $domaine['libelle']
  1118.             ];
  1119.         }
  1120.     
  1121.         $apiUrl 'https://graph.facebook.com/v22.0/870067449513702/messages';
  1122.         $token 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
  1123.         $payload = [
  1124.             "messaging_product" => "whatsapp",
  1125.             "to" => $number,
  1126.             "type" => "interactive",
  1127.             "interactive" => [
  1128.                 "type" => "list",
  1129.                 "body" => [
  1130.                     "text" => $text
  1131.                 ],
  1132.                 "footer" => [
  1133.                     "text" => "Pour arrêter le processus tapez merci ou au revoir"
  1134.                 ],
  1135.                 "action" => [
  1136.                     "button" => "Choisir un domaine",
  1137.                     "sections" => [
  1138.                         [
  1139.                             "title" => "domaine disponibles",
  1140.                             "rows" => $messageListe
  1141.                         ]
  1142.                     ]
  1143.                 ]
  1144.             ]
  1145.         ];
  1146.         try {
  1147.             $response $this->client->request('POST'$apiUrl, [
  1148.                 'headers' => [
  1149.                     'Authorization' => 'Bearer ' $token,
  1150.                     'Content-Type' => 'application/json',
  1151.                 ],
  1152.                 'json' => $payload,
  1153.             ]);
  1154.             return $response->toArray();
  1155.         } catch (\Exception $e) {
  1156.             return ['error' => $e->getMessage()];
  1157.         }
  1158.     }
  1159.     public function EnvoyerListeThematique($choix$number)
  1160.     {
  1161.         // Authentification
  1162.         $auth $this->fonct->execPost('''api/authentification'json_encode(["email"=> "djafarasakinatou@gmail.com","password"=> "l2323"]));
  1163.         //thématiques
  1164.         $responseThematique $this->fonct->execPost($auth['data']['token'],'api/appuis/conseil/theme',json_encode(["id_domaine" => $choix]));
  1165.         //$this->envoyerSimpleMessage("DEBUG : \n" . json_encode($responseThematique), $number);
  1166.         if (!isset($responseThematique['data'])) {
  1167.             $this->envoyerSimpleMessage("Aucune donnée trouvée pour cette commune."$number);
  1168.             return;
  1169.         }
  1170.         // texte
  1171.         $msg "📚 *Veuillez choisir une thématique :*\n\n";
  1172.         foreach ($responseThematique['data'] as $theme) {
  1173.             $msg .= "👉 Tapez *{$theme['N°']}* pour *{$theme['libelle']}*\n";
  1174.         }
  1175.         $msg .= "\nPour arrêter tapez *merci* ou *au revoir*.";
  1176.         // Envoyer
  1177.         $this->envoyerSimpleMessage($msg$number);
  1178.     }
  1179.     public function thematiqueTrouver($domaine): array 
  1180.     {  
  1181.         // Authentification
  1182.         $auth $this->fonct->execPost('','api/authentification',json_encode([
  1183.                 "email"=> "djafarasakinatou@gmail.com",
  1184.                 "password"=> "l2323"
  1185.             ])
  1186.         );
  1187.         // Vérification authentification
  1188.         if (!isset($auth['data']['token'])) {
  1189.             return [];
  1190.         }
  1191.         $token $auth['data']['token'];
  1192.         // Récupération thématiques
  1193.         $response $this->fonct->execPost($token,'api/appuis/conseil/theme',json_encode(["id_domaine" => $domaine]));
  1194.         // Vérification statuts
  1195.         if (!isset($response['status']) || $response['status'] !== 200) {
  1196.             return [];
  1197.         }
  1198.         // Retour du tableau des thématiques
  1199.         return $response['data'] ?? [];
  1200.     }
  1201.     #[Route('/envoyer/fichier'name'app_envoyer_fichier'methods: ['POST'])]
  1202.     public function envoyerFichier(Request $requestEntityManagerInterface $entityManagerUserRepository $UserRepository): Response
  1203.     {
  1204.         $data json_decode($request->getContent(), true);
  1205.         $obligatoire = ['id_theme','numero'];
  1206.         foreach ($obligatoire as $champs) {
  1207.             if (empty($data[$champs])) {
  1208.                 return $this->json([
  1209.                     'status' => 400,
  1210.                     'message' => 'failed',
  1211.                     'data' => ['error_message' => "Le champ $champs est obligatoire."],
  1212.                 ]);
  1213.             }
  1214.         }
  1215.         $apiUrl 'https://graph.facebook.com/v22.0/870067449513702/messages';
  1216.         $token  'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
  1217.         // Authentification interne
  1218.         $auth $this->fonct->execPost('''api/authentification'json_encode([
  1219.             "email"=> "djafarasakinatou@gmail.com",
  1220.             "password"=> "l2323"
  1221.         ]));
  1222.         // Récupération des fichiers
  1223.         $responsefichiers $this->fonct->execPost(
  1224.             $auth['data']['token'],
  1225.             'api/appuis/conseil/fichier',
  1226.             json_encode(["id_theme"=> $data['id_theme']])
  1227.         );
  1228.         if (!isset($responsefichiers['data']) || empty($responsefichiers['data'])) {
  1229.             return $this->json(['status' => 400'message' => 'Aucun fichier trouvé']);
  1230.         }
  1231.         //dd($responsefichiers);
  1232.         $dataFichier = [];
  1233.         // $i=0;
  1234.         foreach ($responsefichiers['data'] as $item) {
  1235.             
  1236.             $dataFichier[] = [
  1237.                 'conseil'=>$item['conseil'],
  1238.                 'fichier'=>$item['fichier'],
  1239.                 'semaine'=>$item['semaine'],
  1240.                 'date_ajout'=>$item['date_ajout'],
  1241.             ];
  1242.             $extension pathinfo($item['fichier'], PATHINFO_EXTENSION);
  1243.             // dd($extension);
  1244.             $payload = [
  1245.                 "to" => $data['numero'],
  1246.                 "type" => "template",
  1247.                 "messaging_product" => "whatsapp",
  1248.                 "template" => [
  1249.                     "name" => "model_garbal_format_document",
  1250.                     "language" => ["code" => "fr"],
  1251.                     "components" => [
  1252.                         [
  1253.                             "type" => "header",
  1254.                             "parameters" => [
  1255.                                 [
  1256.                                     "type" => "document",
  1257.                                     "document" => [
  1258.                                         "link" => $item['fichier'],
  1259.                                         "filename" => $item['conseil']
  1260.                                     ]
  1261.                                 ]
  1262.                             ]
  1263.                         ],
  1264.                         [
  1265.                             "type" => "body",
  1266.                             "parameters" => [
  1267.                                 [
  1268.                                     "type" => "text",
  1269.                                     "text" => $item['conseil']
  1270.                                 ]
  1271.                             ]
  1272.                         ]
  1273.                     ]
  1274.                 ]
  1275.             ];
  1276.             $ch curl_init();
  1277.             curl_setopt($chCURLOPT_URL$apiUrl);
  1278.             curl_setopt($chCURLOPT_HTTPHEADER, [
  1279.                 'Authorization: Bearer '.$token,
  1280.                 'Content-Type: application/json'
  1281.             ]);
  1282.             curl_setopt($chCURLOPT_POSTFIELDSjson_encode($payload));
  1283.             curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  1284.             $response curl_exec($ch);
  1285.             $error curl_error($ch);
  1286.             curl_close($ch);
  1287.             file_put_contents("whatsapp_response.log""RESPONSE: ".$response." | ERROR: ".$error.PHP_EOLFILE_APPEND);
  1288.             // usleep(300000); // pause 0.3s pour ne pas se faire bloquer
  1289.         }
  1290.         
  1291.         return $this->json([
  1292.             'status' => 200,
  1293.             'message' => 'Fichiers envoyés avec succès'
  1294.             // 'data' => $dataFichier
  1295.         ]);
  1296.     }
  1297.     public function envoyerFichierTheme($numero$id_theme)
  1298.     {
  1299.         $apiUrl 'https://graph.facebook.com/v22.0/870067449513702/messages';
  1300.         $token  'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
  1301.         // Authentification interne
  1302.         $auth $this->fonct->execPost('''api/authentification'json_encode([
  1303.             "email"=> "djafarasakinatou@gmail.com",
  1304.             "password"=> "l2323"
  1305.         ]));
  1306.         //$this->envoyerSimpleMessage("Aucune donnée trouvée pour cette commune.", $numero);
  1307.             
  1308.         // Récupération des fichiers
  1309.         $responsefichiers $this->fonct->execPost(
  1310.             $auth['data']['token'],
  1311.             'api/appuis/conseil/fichier',
  1312.             json_encode(["id_theme"=> $id_theme])
  1313.         );
  1314.         //$this->envoyerSimpleMessage("DEBUG : \n" . json_encode($responsefichiers), $numero);
  1315.         if (!isset($responsefichiers['data']) || empty($responsefichiers['data'])) {
  1316.             $this->envoyerSimpleMessage("Aucune donnée trouvée ."$numero);
  1317.             return;
  1318.         }
  1319.         //dd($responsefichiers);
  1320.         $dataFichier = [];
  1321.         // $i=0;
  1322.         foreach ($responsefichiers['data'] as $item) {
  1323.             
  1324.             $dataFichier[] = [
  1325.                 'conseil'=>$item['conseil'],
  1326.                 'fichier'=>$item['fichier'],
  1327.                 'semaine'=>$item['semaine'],
  1328.                 'date_ajout'=>$item['date_ajout'],
  1329.             ];
  1330.             $extension pathinfo($item['fichier'], PATHINFO_EXTENSION);
  1331.             // dd($extension);
  1332.             $payload = [
  1333.                 "to" => $numero,
  1334.                 "type" => "template",
  1335.                 "messaging_product" => "whatsapp",
  1336.                 "template" => [
  1337.                     "name" => "model_garbal_format_document",
  1338.                     "language" => ["code" => "fr"],
  1339.                     "components" => [
  1340.                         [
  1341.                             "type" => "header",
  1342.                             "parameters" => [
  1343.                                 [
  1344.                                     "type" => "document",
  1345.                                     "document" => [
  1346.                                         "link" => $item['fichier'],
  1347.                                         "filename" => $item['conseil']
  1348.                                     ]
  1349.                                 ]
  1350.                             ]
  1351.                         ],
  1352.                         [
  1353.                             "type" => "body",
  1354.                             "parameters" => [
  1355.                                 [
  1356.                                     "type" => "text",
  1357.                                     "text" => $item['conseil']
  1358.                                 ]
  1359.                             ]
  1360.                         ]
  1361.                     ]
  1362.                 ]
  1363.             ];
  1364.             $ch curl_init();
  1365.             curl_setopt($chCURLOPT_URL$apiUrl);
  1366.             curl_setopt($chCURLOPT_HTTPHEADER, [
  1367.                 'Authorization: Bearer '.$token,
  1368.                 'Content-Type: application/json'
  1369.             ]);
  1370.             curl_setopt($chCURLOPT_POSTFIELDSjson_encode($payload));
  1371.             curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  1372.             $response curl_exec($ch);
  1373.             $error curl_error($ch);
  1374.             curl_close($ch);
  1375.             file_put_contents("whatsapp_response.log""RESPONSE: ".$response." | ERROR: ".$error.PHP_EOLFILE_APPEND);
  1376.             // usleep(300000); // pause 0.3s pour ne pas se faire bloquer
  1377.         }
  1378.     }
  1379.     
  1380.      public function envoyerMessagePlusDocument(string $numerostring $nombre)
  1381.     {
  1382.         $apiUrl 'https://graph.facebook.com/v22.0/870067449513702/messages';
  1383.         $token =  'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcS';
  1384.         
  1385.         $payload = [
  1386.             "messaging_product" => "whatsapp",
  1387.             "to" => "$numero",
  1388.             "type" => "template",
  1389.             "template" => [
  1390.                 "name" => "model_garbal_format_document ",
  1391.                 "language" => ["code" => "FR"],
  1392.                 "components" => [
  1393.                     [
  1394.                         "type" => "body",
  1395.                         "parameters" => [
  1396.                             ["type" => "text""text" => $nombre],
  1397.                         ],
  1398.                     ],
  1399.                 ],
  1400.             ],
  1401.         ];
  1402.         try {
  1403.             $response $this->client->request('POST'$apiUrl, [
  1404.                 'headers' => [
  1405.                     'Authorization' => 'Bearer ' $token,
  1406.                     'Content-Type' => 'application/json',
  1407.                 ],
  1408.                 'json' => $payload,
  1409.             ]);
  1410.             return $response->toArray(); 
  1411.         } catch (\Exception $e) {
  1412.             return ['error' => $e->getMessage()];
  1413.         }
  1414.     }
  1415.     
  1416.     private function validateToken(Request $requestJWTEncoderInterface $JWTDecodeManagerEntityManagerInterface $entityManagerUserRepository $UserRepository)
  1417.     {
  1418.         $authorizationHeader $request->headers->get('Authorization');
  1419.         if (!$authorizationHeader) {
  1420.             return new JsonResponse(['status' => 401'message' => 'Token non fourni'], 401);
  1421.         }
  1422.         $tokenParts explode(' '$authorizationHeader);
  1423.         if (count($tokenParts) !== || $tokenParts[0] !== 'Bearer') {
  1424.             return new JsonResponse(['status' => 401'message' => 'Format du token invalide'], 401);
  1425.         }
  1426.         $token $tokenParts[1];
  1427.         try {
  1428.             $userData $JWTDecodeManager->decode($token);
  1429.         } catch (\Exception $e) {
  1430.             return new JsonResponse(['status' => 401'message' => 'Token invalide'], 401);
  1431.         }
  1432.         if (!isset($userData['username'])) {
  1433.             return new JsonResponse(['status' => 401'message' => 'Token mal formé (username manquant)'], 401);
  1434.         }
  1435.         // dd($userData);
  1436.         $user $UserRepository->findOneBy(['email' => $userData['username']]);
  1437.         
  1438.         if (!$user) {
  1439.             return new JsonResponse(['status' => 401'message' => 'Utilisateur non trouvé'], 401);
  1440.         }
  1441.         if ($user->getStatut() != 1) {
  1442.             return new JsonResponse(['status' => 401'message' => 'Compte inactif'], 401);
  1443.         }
  1444.         if (isset($userData['exp']) && $userData['exp'] < time()) {
  1445.         return new JsonResponse(['status' => 401'message' => 'Token expiré'], 401);
  1446.         }
  1447.         // Tout est bon, on retourne les infos de l'utilisateur
  1448.         return [
  1449.             'id'    => $user->getId(),
  1450.             'role'  => $user->getRoles(),
  1451.             'email' => $user->getEmail()
  1452.         ];
  1453.     }
  1454. }