src/Controller/APIIctus/APIIctPanierController.php line 467

Open in your IDE?
  1. <?php
  2. namespace App\Controller\APIIctus;
  3. use DateTime;
  4. use App\Entity\User;
  5. use App\Entity\Carte;
  6. use App\Services\Util;
  7. use App\Entity\Ordonnance;
  8. use App\Entity\PrisEnCharge;
  9. use App\Entity\IctusCommande;
  10. use App\Entity\IctusPharmacie;
  11. use App\Entity\Stockpharmacie;
  12. use App\Services\MailerServices;
  13. use App\Entity\IctusCommandeLine;
  14. use App\Services\IctocoinService;
  15. use App\Entity\IctusPanierPatient;
  16. use App\Entity\IctusPanierSpecial;
  17. use App\Repository\UserRepository;
  18. use App\Entity\RemiseUserPharmacie;
  19. use App\Repository\CarteRepository;
  20. use App\Services\api\PanierService;
  21. use App\Services\api\RemiseService;
  22. use App\Repository\AdhererRepository;
  23. use App\Services\NotificationService;
  24. use App\Repository\AssuranceRepository;
  25. use App\Services\FacturePatientService;
  26. use App\Repository\OrdonnanceRepository;
  27. use App\Services\VanillaPaiementSercice;
  28. use Doctrine\ORM\EntityManagerInterface;
  29. use App\Services\CodeRecuperationService;
  30. use App\Repository\TypepaiementRepository;
  31. use App\Repository\IctusCommandeRepository;
  32. use App\Repository\IctusPharmacieRepository;
  33. use App\Repository\StockpharmacieRepository;
  34. use Symfony\Component\HttpFoundation\Request;
  35. use Symfony\Component\Mailer\MailerInterface;
  36. use App\Repository\EtatPrisenchargeRepository;
  37. use Symfony\Component\HttpFoundation\Response;
  38. use App\Repository\IctusEtatPaiementRepository;
  39. use App\Repository\IctusTypePaiementRepository;
  40. use Symfony\Component\Routing\Annotation\Route;
  41. use App\Repository\IctusPanierPatientRepository;
  42. use App\Repository\IctusPanierSpecialRepository;
  43. use App\Repository\IctusTypeLivraisonRepository;
  44. use App\Repository\IctusMobileAppareilRepository;
  45. use App\Repository\RemiseUserPharmacieRepository;
  46. use App\Services\VanillaPayInternationnalService;
  47. use Symfony\Component\HttpFoundation\JsonResponse;
  48. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  49. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  50. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  51. #[Route('/api/ictus-shop/panier'name'app_api_ictus_shop_panier_')]
  52. class APIIctPanierController extends AbstractController
  53. {
  54.     private $em;
  55.     private $mailerint;
  56.     private $mailTechnicien "zoanja.rabehaja@sopharmad.mg";
  57.     private $util;
  58.     private $montantTotalPaiementEnLigne 0;
  59.     private $listeCommandePaiementEnLigne = array();
  60.     private $notifUrl;
  61.     private $redirectUrl;
  62.     public function __construct(EntityManagerInterface $emMailerInterface $mailerintUtil $utilUrlGeneratorInterface $urlGenerator)
  63.     {
  64.         $this->em $em;
  65.         $this->mailerint  $mailerint;
  66.         $this->util       $util;
  67.         $this->notifUrl   $_ENV["VANILLA_INT_URL_NOTIF"];
  68.         $this->redirectUrl $_ENV["VANILLA_INT_URL_REDIRECT"];
  69.     }
  70.     #[Route('/non-authentifier'name'non_auth'methods: ['GET'])]
  71.     public function panierNonAuth(Request $requestStockpharmacieRepository $stockpharmacieRepositoryPanierService $panierService): Response
  72.     {
  73.         $produitPcie $request->query->all('produitPcie');
  74.         $produitPcie array_map('intval'$produitPcie);
  75.         $panierCart  $panierService->getFull($stockpharmacieRepositorynull,$produitPcie);
  76.         $responseData   = [
  77.             'error' => true,
  78.         ];
  79.         if (count($panierService->groupByIdPcie($panierCart)) > 0) {
  80.             $responseData $panierService->groupByIdPcie($panierCart);
  81.             return $this->json($responseData);
  82.         }
  83.         return $this->json($responseData500, [], []);
  84.     }
  85.     /******************Ajouter panier dans MySQL************** */
  86.     //Enregistrement panier direct dans DB MysQl par l'user connectee dans meilleur vente
  87.     #[Route('/ajout-auth-mysql'name'app_panier_add_auth'methods: ['POST'])]
  88.     public function ajoutPanierAuthBestSeller(Request $requestIctusPanierPatientRepository $panierRepoUserRepository $userRepositoryStockpharmacieRepository $stockPcieRepo): Response
  89.     {
  90.         // Récupérer les données du corps de la requête
  91.         $data json_decode($request->getContent(), true);
  92.         // Vérifier si userId est bien envoyé
  93.         if (!isset($data['userId'])) {
  94.             return $this->json(['error' => 'ID utilisateur manquant'], JsonResponse::HTTP_BAD_REQUEST);
  95.         }
  96.         // Vérifier si les produits sont bien envoyés
  97.         if (!isset($data['produit'])) {
  98.             return $this->json(['error' => 'Aucun produit fourni'], JsonResponse::HTTP_BAD_REQUEST);
  99.         }
  100.         // Récupérer l'utilisateur depuis l'ID envoyé
  101.         $user $userRepository->find($data['userId']);
  102.         if (!$user) {
  103.             return $this->json(['error' => 'Utilisateur non trouvé'], JsonResponse::HTTP_NOT_FOUND);
  104.         }
  105.         if (!isset($data['produit'], $data['quantite'])) {
  106.             return $this->json(['error' => 'Informations du produit manquantes'], JsonResponse::HTTP_BAD_REQUEST);
  107.         }
  108.         // Récupérer le produit en base de données
  109.         $produit $stockPcieRepo->find($data['produit']);
  110.         if (!$produit) {
  111.             return $this->json(['error' => 'Produit non trouvé'], JsonResponse::HTTP_NOT_FOUND);
  112.         }
  113.         // produit exit panier ou non 
  114.         $existPanier   $panierRepo->findOneBy(['user' => $user'produit_stock_pcie' => $produit]);
  115.         $quantite      $data['quantite'];
  116.         $tva           $produit->getTva();
  117.         if (!is_null($existPanier)) {
  118.             $quantite $existPanier->getQuantite() + $data['quantite'];
  119.         }
  120.         $panier        = (!is_null($existPanier)) ? $existPanier : new IctusPanierPatient();
  121.         // Calculer le prix total
  122.         $prix_unitaire = (!is_null($tva)) ? ($produit->getPrixunitforme() + ($produit->getPrixunitforme() * $tva) / 100) : $produit->getPrixunitforme();
  123.         // Créer une nouvelle entrée dans le panier
  124.         $panier->setProduitStockPcie($produit)
  125.             ->setUser($user)
  126.             ->setQuantite($quantite)
  127.             ->setPrixUnitaire($prix_unitaire)
  128.             ->setTotal($quantite $prix_unitaire);
  129.         // Persister dans la base de données
  130.         $this->em->persist($panier);
  131.         $this->em->flush();
  132.         return $this->json(['message' => 'Panier enregistré avec succès'], JsonResponse::HTTP_CREATED);
  133.     }
  134.     //Enregistrement panier SQLite dans DB MysQl apres login
  135.     #[Route('/ajout-sqlit-mysql'name'app_panier_add_sqlite_to_mysql_apre_login'methods: ['POST'])]
  136.     public function enregistrementPanierDB(
  137.         Request $request,
  138.         StockpharmacieRepository $stockPcieRepo,
  139.         UserRepository $userRepo,
  140.         IctusPanierPatientRepository $panierRepo,
  141.         EntityManagerInterface $em
  142.     ): JsonResponse {
  143.         // Récupérer les données du corps de la requête
  144.         $data json_decode($request->getContent(), true);
  145.         // Vérifier si userId est bien envoyé
  146.         if (!isset($data['userId'])) {
  147.             return $this->json(['error' => 'ID utilisateur manquant'], JsonResponse::HTTP_BAD_REQUEST);
  148.         }
  149.         // Vérifier si les produits sont bien envoyés
  150.         if (!isset($data['produits']) || !is_array($data['produits'])) {
  151.             return $this->json(['error' => 'Aucun produit fourni'], JsonResponse::HTTP_BAD_REQUEST);
  152.         }
  153.         $user $userRepo->findOneById($data['userId']);
  154.         if (!$user) {
  155.             return $this->json(['error' => 'Utilisateur: '.$data['userId'].' non trouvé'], JsonResponse::HTTP_NOT_FOUND);
  156.         }
  157.         $paniers $data['produits'];
  158.         $prixTotal 0;
  159.         foreach ($paniers as $panierSession) {
  160.             // Vérifier les informations du produit
  161.             if (!isset($panierSession['idProduit'], $panierSession['quantite'])) {
  162.                 return $this->json(['error' => 'Informations du produit manquantes'], JsonResponse::HTTP_BAD_REQUEST);
  163.             }
  164.             // Récupérer le produit en base de données
  165.             $produit $stockPcieRepo->find($panierSession['idProduit']);
  166.             if (!$produit) {
  167.                 return $this->json(['error' => 'Produit non trouvé'], JsonResponse::HTTP_NOT_FOUND);
  168.             }
  169.             $existPanier   $panierRepo->findOneBy(['user' => $user'produit_stock_pcie' => $produit]);
  170.             $quantite      $panierSession['quantite'];
  171.             $tva           $produit->getTva();
  172.             if (!is_null($existPanier)) {
  173.                 $quantite  $existPanier->getQuantite() + $panierSession['quantite'];
  174.             }
  175.             $panier        = (!is_null($existPanier)) ? $existPanier : new IctusPanierPatient();
  176.             $prix_unitaire = (!is_null($tva)) ? ($produit->getPrixunitforme() + ($produit->getPrixunitforme() * $tva) / 100) : $produit->getPrixunitforme();
  177.             $prixTotal += $quantite $prix_unitaire;
  178.             // Créer une nouvelle entrée dans le panier
  179.             $panier->setProduitStockPcie($produit)
  180.                 ->setUser($user)
  181.                 ->setQuantite($quantite)
  182.                 ->setPrixUnitaire($prix_unitaire)
  183.                 ->setTotal($quantite $prix_unitaire);
  184.             // Essayer de persister chaque entrée
  185.             try {
  186.                 $em->persist($panier);
  187.             } catch (\Exception $e) {
  188.                 // Logger l'erreur avec plus de détails
  189.                 return $this->json(['erreur' => 'Erreur lors de l\'ajout au panier: ' $e->getMessage()], JsonResponse::HTTP_INTERNAL_SERVER_ERROR);
  190.             }
  191.         }
  192.         // Enregistrer tous les paniers en une seule transaction
  193.         try {
  194.             $em->flush();
  195.         } catch (\Exception $e) {
  196.             return $this->json(['erreur' => 'Erreur lors de l\'enregistrement des paniers: ' $e->getMessage()], JsonResponse::HTTP_INTERNAL_SERVER_ERROR);
  197.         }
  198.         return $this->json(['message' => 'Panier ajouté avec succès''total' => $prixTotal], JsonResponse::HTTP_CREATED);
  199.     }
  200.     #[Route('/count-mysql'name'app_panier_count_mysql'methods: ['POST'])]
  201.     public function getCountProduitParUser(Request $requestUserRepository $userRepoIctusPanierPatientRepository $panierRepo)
  202.     {
  203.         $data json_decode($request->getContent(), true);
  204.         if (!isset($data['userId'])) {
  205.             return $this->json(['error' => 'ID utilisateur manquant'], JsonResponse::HTTP_BAD_REQUEST);
  206.         }
  207.         $user $userRepo->find($data['userId']);
  208.         if (!$user) {
  209.             return $this->json(['error' => 'Utilisateur non trouvé'], JsonResponse::HTTP_NOT_FOUND);
  210.         }
  211.         $countPanier $panierRepo->findCountpanierByUser($user);
  212.         return $this->json(["countPanier" => $countPanier]);
  213.     }
  214.     //Liste produit dans panier MySQL pour l'utilisateur connecte
  215.     #[Route('/mysql-user-connecte'name'mysql_user_connecte'methods: ['POST'])]
  216.     public function panierMySQLUserConnectee(
  217.         Request $request,
  218.         StockpharmacieRepository $stockpharmacieRepository,
  219.         PanierService $panierService,
  220.         IctusPanierPatientRepository $panierRepo,
  221.         UserRepository $userRepo
  222.     ): Response {
  223.         $data json_decode($request->getContent(), true);
  224.         if (!isset($data['userId'])) {
  225.             return $this->json(['error' => 'ID utilisateur manquant'], JsonResponse::HTTP_BAD_REQUEST);
  226.         }
  227.         $user             $userRepo->find($data['userId']);
  228.         $produitPcie      $panierRepo->findAllByUser($user);
  229.         $coupleIdQuantite = [];
  230.         if (count($produitPcie) > 0) {
  231.             foreach ($produitPcie as $panier) {
  232.                 $idStockPcie                    $panier->getProduitStockPcie()->getId();
  233.                 $quantite                       $panier->getQuantite();
  234.                 $coupleIdQuantite[$idStockPcie] = $quantite;
  235.             }
  236.         }
  237.         $panierCart   $panierService->getFull($stockpharmacieRepository$user$coupleIdQuantite);
  238.         $responseData = [
  239.             'error' => true,
  240.         ];
  241.         if (count($panierService->groupByIdPcie($panierCart)) > 0) {
  242.             $responseData $panierService->groupByIdPcie($panierCart);
  243.             return $this->json($responseDataJsonResponse::HTTP_OK);
  244.         }
  245.         return $this->json(['error' => 'Empty Data'], JsonResponse::HTTP_NOT_FOUND);
  246.     }
  247.     #[Route('/mysql-user-connecte-update-quantite'name'mysql_user_connecte_update_quantite'methods: ['POST'])]
  248.     public function updateQuantiteProduitPanier(
  249.         Request $request,
  250.         StockpharmacieRepository $stockpharmacieRepository,
  251.         IctusPanierPatientRepository $panierRepo,
  252.         UserRepository $userRepo
  253.     ): Response {
  254.         $data      json_decode($request->getContent(), true);
  255.         $panier    null;
  256.         $stockpcie null;
  257.         if (!isset($data['userId'])) {
  258.             return $this->json(['error' => 'ID utilisateur manquant'], JsonResponse::HTTP_BAD_REQUEST);
  259.         }
  260.         $user $userRepo->find($data['userId']);
  261.         if (is_null($user)) {
  262.             return $this->json(['error' => 'User non trouve'], JsonResponse::HTTP_NOT_FOUND);
  263.         }
  264.         if (!isset($data['produit'])) {
  265.             return $this->json(['error' => 'ID Produit manquant'], JsonResponse::HTTP_BAD_REQUEST);
  266.         }
  267.         $stockpcie $stockpharmacieRepository->findOneById($data['produit']);
  268.         if (is_null($stockpcie)) {
  269.             return $this->json(['error' => 'Produit non trouve'], JsonResponse::HTTP_NOT_FOUND);
  270.         }
  271.         $panier $panierRepo->findOneBy(['produit_stock_pcie' => $stockpcie'user' => $user]);
  272.         /******* */
  273.         $tva           $stockpcie->getTva();
  274.         $prix_unitaire = (!is_null($tva)) ? ($stockpcie->getPrixunitforme() + ($stockpcie->getPrixunitforme() * $tva) / 100) : $stockpcie->getPrixunitforme();
  275.         $pixTotal      =  $prix_unitaire $data['quantite'];
  276.         /************ */
  277.         if (!is_null($panier)) {
  278.             $panier->setQuantite($data['quantite'])
  279.                 ->setTotal($pixTotal)
  280.                 ->setPrixUnitaire($prix_unitaire);
  281.             $this->em->flush();
  282.             $newData = [
  283.                 'userId'        => $data['userId'],
  284.                 'produit'       => $data['produit'],
  285.                 'quantite'      => $data['quantite'],
  286.                 'prix_unitaire' => $prix_unitaire,
  287.                 'total'         => $pixTotal
  288.             ];
  289.             return $this->json($newDataJsonResponse::HTTP_OK);
  290.         }
  291.         return $this->json(['error' => 'Empty Data'], JsonResponse::HTTP_NOT_FOUND);
  292.     }
  293.     #[Route('/mysql-user-connecte-delete'name'mysql_user_connecte_delete'methods: ['POST'])]
  294.     public function deleteProduitPanierMySQL(
  295.         Request $request,
  296.         StockpharmacieRepository $stockpharmacieRepository,
  297.         IctusPanierPatientRepository $panierRepo,
  298.         UserRepository $userRepo
  299.     ): Response {
  300.         $data      json_decode($request->getContent(), true);
  301.         $panier    null;
  302.         $stockpcie null;
  303.         if (!isset($data['userId'])) {
  304.             return $this->json(['error' => 'ID utilisateur manquant'], JsonResponse::HTTP_BAD_REQUEST);
  305.         }
  306.         $user $userRepo->find($data['userId']);
  307.         if (is_null($user)) {
  308.             return $this->json(['error' => 'User non trouve'], JsonResponse::HTTP_NOT_FOUND);
  309.         }
  310.         if (!isset($data['produit'])) {
  311.             return $this->json(['error' => 'ID Produit manquant'], JsonResponse::HTTP_BAD_REQUEST);
  312.         }
  313.         $stockpcie $stockpharmacieRepository->findOneById($data['produit']);
  314.         if (is_null($stockpcie)) {
  315.             return $this->json(['error' => 'Produit non trouve'], JsonResponse::HTTP_NOT_FOUND);
  316.         }
  317.         $panier $panierRepo->findOneBy(['produit_stock_pcie' => $stockpcie'user' => $user]);
  318.         /************ */
  319.         if (!is_null($panier)) {
  320.             $this->em->remove($panier);
  321.             $this->em->flush();
  322.             return $this->json("DATA DELETED OK"JsonResponse::HTTP_OK);
  323.         }
  324.         return $this->json(['error' => 'Empty Data'], JsonResponse::HTTP_NOT_FOUND);
  325.     }
  326.     //Ajouter ordonnace dans un produit panier
  327.     #[Route('/create/ordonnance'name'create_ordonnance'methods: ['POST'])]
  328.     public function createOrdonnancePanier(
  329.         Request $request,
  330.         OrdonnanceRepository $ordonaceRepo,
  331.         PanierService $panierService,
  332.         StockpharmacieRepository $stockpharmacieRepository,
  333.         IctusPanierPatientRepository $panierRepo,
  334.         UserRepository $userRepo
  335.     ): Response {
  336.         //$data = json_decode($request->getContent(), true);
  337.         $panierData $panierService->handleDataPanier($userRepo$stockpharmacieRepository$panierRepo$request);
  338.         if (isset($panierData['error'])) {
  339.             return $this->json($panierDataJsonResponse::HTTP_BAD_REQUEST);
  340.         }
  341.         // Si tout est correct, vous pouvez procéder à la création de l'ordonnance
  342.         $user $panierData['user'];
  343.         if ($user instanceof User) {
  344.             $panier $panierData['panier'];
  345.             if (!is_null($panier) && $panier instanceof IctusPanierPatient) {
  346.                 $panier->setOrdonnance($ordonaceRepo->createOrdonnance($panierData['file'], $panierData['titre'], $panierData['user']));
  347.                 $this->em->flush();
  348.             } else {
  349.                 $ordonaceRepo->createOrdonnance($panierData['file'], $panierData['titre'], $panierData['user']);
  350.             }
  351.             return $this->json(['CREATED' => "DATA CREATE OK"], JsonResponse::HTTP_CREATED);
  352.         }
  353.         return $this->json(['error' => 'Empty Data'], JsonResponse::HTTP_NOT_FOUND);
  354.     }
  355.     //allOrdonneByIdUser()
  356.     #[Route('/ordonnance/{id}'name'get_ordonnance'methods: ['GET'])]
  357.     public function recupOrdonnanceByUser(User $userOrdonnanceRepository $ordonaceRepo): Response
  358.     {
  359.         $dataOrdonnances = [];
  360.         if (!is_null($user)) {
  361.             $ordonnances $ordonaceRepo->findAllOrdonnanceByIdUser($user->getId());
  362.             if (count($ordonnances)) {
  363.                 foreach ($ordonnances as $ordo) {
  364.                     $dataOrd = [
  365.                         'id'     => $ordo->getId(),
  366.                         'userId' => $ordo->getPropriertaire()->getId(),
  367.                         'titre'  => $ordo->getTitre(),
  368.                         'file'   => $ordo->getFichier()
  369.                     ];
  370.                     array_push($dataOrdonnances$dataOrd);
  371.                 }
  372.                 return $this->json($dataOrdonnancesJsonResponse::HTTP_OK);
  373.             }
  374.         }
  375.         return $this->json(['error' => 'Empty Data'], JsonResponse::HTTP_NOT_FOUND);
  376.     }
  377.     //Update PanierOrdonnace
  378.     #[Route('/update/ordonnance'name'update_ordonnance'methods: ['POST'])]
  379.     public function updateOrdonnancePanier(
  380.         Request $request,
  381.         OrdonnanceRepository $ordonaceRepo,
  382.         StockpharmacieRepository $stockpharmacieRepository,
  383.         IctusPanierPatientRepository $panierRepo,
  384.         UserRepository $userRepo
  385.     ): Response {
  386.         $data json_decode($request->getContent(), true);
  387.         if (!isset($data['produitId'])) {
  388.             return $this->json(['error' => 'Produit manquant'], JsonResponse::HTTP_BAD_REQUEST);
  389.         }
  390.         $stockpcie $stockpharmacieRepository->findOneById($data['produitId']);
  391.         if (!isset($data['userId'])) {
  392.             return $this->json(['error' => 'ID utilisateur manquant'], JsonResponse::HTTP_BAD_REQUEST);
  393.         }
  394.         $user $userRepo->find($data['userId']);
  395.         $panier $panierRepo->findOneBy(['produit_stock_pcie' => $stockpcie'user' => $user]);
  396.         if (!isset($data['ordonnanceId'])) {
  397.             return $this->json(['error' => 'Id ordonnance manquant'], JsonResponse::HTTP_BAD_REQUEST);
  398.         }
  399.         $ordonnance $ordonaceRepo->findOneById($data['ordonnanceId']);
  400.         if ($user instanceof User && $ordonnance instanceof Ordonnance && $panier instanceof IctusPanierPatient) {
  401.             $panier->setOrdonnance($ordonnance);
  402.             $this->em->flush();
  403.             return $this->json(['UPDATED' => "DATA UPDATED OK"], JsonResponse::HTTP_OK);
  404.         }
  405.         return $this->json(['error' => 'Empty Data'], JsonResponse::HTTP_NOT_FOUND);
  406.     }
  407.     /*  url = {base_url}/api/ictus-shop/panier/panier/sendcommande/{userId}/{typeLivraisonId}/{typePaiementId}
  408.         method : GET
  409.      */
  410.     #[Route('/sendcommande/{userId}/{typeLivraisonId}/{typePaiementId}/{assuranceId}'name'panier_sendcommande'methods: ['GET'])]
  411.     public function panierSendcommande(
  412.         Request $requestFacturePatientService $facturePatientService
  413.         IctusMobileAppareilRepository $mobileAppareilRepo
  414.         NotificationService $notificationServiceMailerServices $mail
  415.         IctocoinService $ictocoinServiceVanillaPayInternationnalService $vanillaPayInternationnalService,
  416.         UserRepository $userRepoIctusPanierPatientRepository $ictusPanierPatientRepoIctusTypeLivraisonRepository $ictusTypeLivraisonRepo,
  417.         IctusTypePaiementRepository $ictusTypePaiementRepoIctusPharmacieRepository $ictusPharmacieRepo,
  418.         IctusEtatPaiementRepository $etatPaiementRepoIctusCommandeRepository $ictusCommandeRepo,
  419.         CodeRecuperationService $codeRecuperationService$userId$typeLivraisonId$typePaiementId,
  420.         AssuranceRepository $assuranceRepo,AdhererRepository $adhererRepo,EtatPrisenchargeRepository $etatPrisenchargeRepo,
  421.         $assuranceId null
  422.     ){
  423.         if ($request->isMethod('GET')) {
  424.             $tierPayant null;
  425.             $adherer    null;
  426.         
  427.             $urlPaiement null;
  428.             if ($typeLivraisonId != null && $typePaiementId != null && $userId != null) {
  429.                 $user         $userRepo->find($userId);
  430.                 $token = (new \DateTime())->format('YmdiHs') . $user->getId();
  431.                 $typeLivraison $ictusTypeLivraisonRepo->find($typeLivraisonId);
  432.                 $typePaiement  $ictusTypePaiementRepo->find($typePaiementId);
  433.                 //TierPayant
  434.                 if ($assuranceId != "null" && $assuranceId != 0){
  435.                     $tierPayant  $assuranceRepo->findOneById($assuranceId);
  436.                     $adherer     $adhererRepo->getConditionsAdhererByAssurance($user$tierPayant);
  437.                 }
  438.                 //FIN
  439.                 $paniers    $ictusPanierPatientRepo->findBy(['user' => $user]);
  440.                 if (count($paniers) > 0) {
  441.                     $nbCommandes $this->sendCommande($paniers$typePaiement$typeLivraison$user$ictusPanierPatientRepo$ictusPharmacieRepo$etatPaiementRepo$token$ictusCommandeRepo$codeRecuperationService$ictusTypePaiementRepo$facturePatientService$ictocoinService$mail$notificationService$mobileAppareilRepo,$etatPrisenchargeRepo$tierPayant,$adherer);
  442.                     $ictusPanierPatientRepo->removeProduit($user->getId());
  443.                     if ($nbCommandes 0) {
  444.                         /* Paiement si necessaire */
  445.                         if (count($this->listeCommandePaiementEnLigne) > and $this->montantTotalPaiementEnLigne 0) {
  446.                             $liste json_encode($this->listeCommandePaiementEnLigne);
  447.                             $reference = (new DateTime())->format('YmdHis') . $user->getId();
  448.                             if ($typePaiement->getId() == 4) {
  449.                                 $vanilla   = new VanillaPaiementSercice($this->util);
  450.                                 $nomUser   $user->getNomComplet();
  451.                                 $adresseip $this->getUserIpAddr();
  452.                                 $urlPaiement $vanilla->payer($liste$this->montantWithFrai($this->montantTotalPaiementEnLigne), $nomUser$reference$adresseip);
  453.                                 if ($urlPaiement != null) {
  454.                                     $urlPaiement $urlPaiement->getTargetUrl();
  455.                                 }
  456.                             } else if ($typePaiement->getId() == 5) {
  457.                                 $urlPaiement $vanillaPayInternationnalService->payer($liste$this->montantTotalPaiementEnLigne$reference$this->notifUrl$this->redirectUrl);
  458.                                 if ($urlPaiement != null) {
  459.                                     $urlPaiement $urlPaiement->getTargetUrl();
  460.                                 }
  461.                             }
  462.                         }
  463.                         return $this->json(['success' => 'Success''message' => 'Commandes envoyées avec succès''nbCommandes' => $nbCommandes'urlPaiement' => $urlPaiement], JsonResponse::HTTP_OK);
  464.                     }
  465.                     return $this->json(['error' => 'Error''message' => 'Aucun commande envoyée''nbCommandes' => $nbCommandes'urlPaiement' => $urlPaiement], JsonResponse::HTTP_OK);
  466.                 }
  467.                 return $this->json(['error' => 'Error''message' => 'Panier vide''nbCommandes' => 0'urlPaiement' => $urlPaiement], JsonResponse::HTTP_OK);
  468.             } else {
  469.                 return $this->json(['error' => 'Error''message' => 'Parametre manquant''nbCommandes' => 0'urlPaiement' => $urlPaiement], JsonResponse::HTTP_BAD_REQUEST);
  470.             }
  471.         }
  472.     }
  473.     private function sendCommande(
  474.         $paniers,
  475.         $typePaiement,
  476.         $typeLivraison,
  477.         $user,
  478.         $ictusPanierPatientRepo,
  479.         $ictusPharmacieRepo,
  480.         $etatPaiementRepo,
  481.         $token,
  482.         $ictusCommandeRepo,
  483.         $codeRecuperationService,
  484.         $ictusTypePaiementRepo,
  485.         $facturePatientService,
  486.         $ictocoinService,
  487.         $mail,
  488.         $notificationService,
  489.         $mobileAppareilRepo,
  490.         $etatPrisenchargeRepo,
  491.         $tierPayant,
  492.         $adherer
  493.     ) {
  494.         $etatPaiementDefault $etatPaiementRepo->findOneById(1);
  495.         $pharmacies $ictusPanierPatientRepo->getPcieDistinctByPatientAndTypePaiement($user$typePaiement);
  496.         $nbCommande 0;
  497.         foreach ($pharmacies as $pharmacie) {
  498.             $paiement null;
  499.             if ($pharmacie["idTypePaiement"] != null) {
  500.                 $paiement $typePaiement;
  501.             } else {
  502.                 $paiement $ictusTypePaiementRepo->findOneById(1);
  503.             }
  504.             $maxReference $ictusCommandeRepo->findMaxReference($pharmacie["idpharmacie"])[0]["maxReference"];
  505.             if ($maxReference == null) {
  506.                 $maxReference 0;
  507.             }
  508.             $maxReference = (int)$maxReference 1;
  509.             $createdAt = new DateTime();
  510.             $createdAt->modify('+2 hours');
  511.             $commande  = new IctusCommande();
  512.             //Tierpayant
  513.             if ($tierPayant != null) {
  514.                 $etatDefault $etatPrisenchargeRepo->find(1);
  515.                 $prisencharge = new PrisEnCharge();
  516.                 $prisencharge->setAssurance($tierPayant)
  517.                              ->setEtat($etatDefault)
  518.                              ->setPrisencharge($adherer['prisencharge'])
  519.                              ->setRemarque($adherer['remarque'])
  520.                              ->setNumero($adherer['numero'])
  521.                              ->setFirstName($adherer['prenom'])
  522.                              ->setLastname($adherer['nom']);
  523.                 $commande->setPrisencharge($prisencharge);
  524.             }
  525.             //Fin tierPayant
  526.             $codeComplet $codeRecuperationService->generateCommande();
  527.             $commande->setPharmacie($ictusPharmacieRepo->findOneById(intval($pharmacie["idpharmacie"])))
  528.                 ->setTypeLivraison($typeLivraison)
  529.                 ->setTypePaiement($paiement)
  530.                 ->setUser($user)
  531.                 ->setToken($token)
  532.                 ->setReference($maxReference)
  533.                 ->setEtatpaiement($etatPaiementDefault)
  534.                 ->setCreatedAt($createdAt)
  535.                 ->setIsRecuperer(false)
  536.                 ->setIsValide($pharmacie["isValideAutomatique"])
  537.                 ->setIsValide($pharmacie["isValideAutomatique"])
  538.                 ->setCode($codeComplet['code'])
  539.                 ->setCodeSecret($codeComplet['secret']);
  540.             $this->em->persist($commande);
  541.             $montantTotal 0;
  542.             foreach ($paniers as $panier) {
  543.                 if ($pharmacie["idpharmacie"] == $panier->getProduitStockPcie()->getIctuspharmacie()->getId()) {
  544.                     $commandeLine = new IctusCommandeLine();
  545.                     $commandeLine->setQuantite($panier->getQuantite())
  546.                         ->setDesignation($panier->getProduitStockPcie()->getNomproduit())
  547.                         ->setCip7($panier->getProduitStockPcie()->getCip7())
  548.                         ->setCip13($panier->getProduitStockPcie()->getCip13())
  549.                         ->setPrixunitaire($panier->getPrixUnitaire() ?? 0)
  550.                         ->setRemise($panier->getProduitStockPcie()->getRemise())
  551.                         ->setOrdonnance($panier->getOrdonnance())
  552.                         ->setCommande($commande)
  553.                         ->setIsValide($pharmacie["isValideAutomatique"]);
  554.                     $this->em->persist($commandeLine);
  555.                     $montantTotal += $panier->getPrixUnitaire() * $panier->getQuantite();
  556.                 }
  557.             }
  558.             $this->em->flush();
  559.             $nbCommande++;
  560.             //Creation facture et ictocoin au cas ou
  561.             if ($pharmacie["isValideAutomatique"] != null) {
  562.                 $this->montantTotalPaiementEnLigne += $montantTotal;
  563.                 array_push($this->listeCommandePaiementEnLigne"CMD-" $commande->getId());
  564.                 $facturePatientService->editPatient($commande);
  565.                 $raison 'Frais de gestion sur la commande du ' date("d M Y") . ', Référence :/cmd {{' $commande->getId() . '}}';
  566.                 $montantDebit $ictocoinService->montantIctocoin($pharmacie["idpharmacie"], $montantTotal);
  567.                 $debitage $ictocoinService->debiter($pharmacie["idpharmacie"], $montantDebit$raison);
  568.                 if ($debitage != true) {
  569.                     $templateMail 'emails/erreurIctocoin.html.twig';
  570.                     $paramsMail = [
  571.                         'type'    => "Débit",
  572.                         'erreur' => "<p>Commande numéro : " $commande->getId() . "</p><p>Pharmacie id : " $pharmacie["idpharmacie"] . "</p><p>Montant : " $montantDebit "<sup style='margin-left:5px;'>ICTO</sup></p><p>Raison : " $raison "</p>"
  573.                     ];
  574.                     $objectMail "Erreur mouvement Ictocoin";
  575.                     $mail->sendMail($this->mailerint$this->mailTechnicien"noreply@ictuspharma.com"$objectMail$templateMail$paramsMail);
  576.                 }
  577.             }
  578.             //Notification pharmacie par mail et mobile
  579.             $user_pcie       $ictusPharmacieRepo->findOneById(intval($pharmacie["idpharmacie"]))->getUsers()[0];
  580.             $mobileAppareils $mobileAppareilRepo->findAllToArray($user_pcie);
  581.             $array_cfm_token array_unique((array_column($mobileAppareils"cfm_tokem")));
  582.             if (count($array_cfm_token) > 0) {
  583.                 $data = [
  584.                     'id_commande'  => intval($commande->getId()),
  585.                     'id_pharmacie' => intval($pharmacie["idpharmacie"]),
  586.                     'reference'    => $commande->getReference()
  587.                 ];
  588.                 foreach ($array_cfm_token as $tk) {
  589.                     $textNotif 'Référence commande ICTCMD_MG_' intval($pharmacie["idpharmacie"]) . '_' $commande->getReference();
  590.                     $notificationService->sendNotification($tk'Nouvelle Commande'$textNotif$data);
  591.                 }
  592.             }
  593.             $templateMail 'emails/commandePatient.html.twig';
  594.             $paramsMail = [
  595.                 'nomPatient'    => $user->getLastname(),
  596.                 'prenomPatient' => $user->getFirstname(),
  597.                 'mailPatient'   => $user->getEmail(),
  598.                 'refCommande'   => "ICT_CMD_" $commande->getId(),
  599.                 'linkCommande'  => 'https://www.pharmadexi.com/ictus/commande/patient/detail/' $commande->getId()
  600.             ];
  601.             $objectMail "Commande Ictuspharma : ICT_CMD_" $commande->getId();
  602.             $mail->sendMail($this->mailerint$pharmacie["mail"], "commande@ictuspharma.com"$objectMail$templateMail$paramsMail);
  603.             //Notification patient
  604.             $templateMail 'emails/confirmationCommandePatient.html.twig';
  605.             $paramsMail = [
  606.                 'nomPatient'    => $user->getLastname(),
  607.                 'pharmacie'    => $pharmacie,
  608.                 'listes' => $paniers,
  609.                 'refCommande'   => "ICT_CMD_" $commande->getId()
  610.             ];
  611.             $objectMail "Commande Ictuspharma : ICT_CMD_" $commande->getId();
  612.             $mail->sendMail($this->mailerint$user->getEmail(), "commande@ictuspharma.com"$objectMail$templateMail$paramsMail);
  613.         }
  614.         return $nbCommande;
  615.     }
  616.     //$paiementRepository->findAll()
  617.     #[Route('/type-paiement'name'api_patient_ictus_panier_paiement'methods: ['GET'])]
  618.     public function recupTypePaiement(IctusTypePaiementRepository $typePaiementRepo): Response
  619.     {
  620.         $typePaiements $typePaiementRepo->findAll();
  621.         if ($typePaiements) {
  622.             $dataTypePaiements = [];
  623.             if (count($typePaiements) > 0) {
  624.                 foreach ($typePaiements as $tp) {
  625.                     $dataTypePaiements[] = [
  626.                         'paiementId'   => $tp->getId(),
  627.                         'designation'  => $tp->getDesignation()
  628.                     ];
  629.                 }
  630.                 return new JsonResponse([
  631.                     'success'       => 'Informations recuperées avec succès',
  632.                     'dataTypePaiements' => $dataTypePaiements
  633.                 ], Response::HTTP_OK);
  634.             }
  635.             return new JsonResponse(['error' => 'Accun type paiement trouvé'], Response::HTTP_NOT_FOUND);
  636.         }
  637.         return new JsonResponse(['error' => 'Type paiement non trouvé'], Response::HTTP_NOT_FOUND);
  638.     }
  639.     //pour le paiement tierspayant ==> assurance
  640.     //$paiementRepository->findAll()
  641.     #[Route('/assurance'name'api_patient_ictus_panier_assurance'methods: ['GET'])]
  642.     public function recupAssurance(
  643.         Request $request,
  644.         AssuranceRepository $assuranceRepo,
  645.         UserRepository $userRepository,
  646.         IctusPanierPatientRepository $panierepo,
  647.         CarteRepository $cateRepo
  648.     ): Response {
  649.         $data = [];
  650.         // Support JSON body + fallback query params
  651.         $content $request->getContent();
  652.         if (!empty($content)) {
  653.             $decoded json_decode($contenttrue);
  654.             if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
  655.                 $data $decoded;
  656.             }
  657.         }
  658.         if (empty($data)) {
  659.             $data $request->query->all();
  660.         }
  661.         $patientId $data['user_id'] ?? $data['patient_id'] ?? null;
  662.         if (empty($patientId) || !is_numeric($patientId)) {
  663.             return new JsonResponse(
  664.                 ['error' => 'Paramètre user_id manquant ou invalide'],
  665.                 Response::HTTP_BAD_REQUEST
  666.             );
  667.         }
  668.         $patient $userRepository->find((int)$patientId);
  669.         if (!$patient) {
  670.             return new JsonResponse(
  671.                 ['error' => 'Patient non trouvé'],
  672.                 Response::HTTP_NOT_FOUND
  673.             );
  674.         }
  675.         // Récupérer les pharmacies distinctes présentes dans le panier
  676.         $latitudePatient null;
  677.         $longitudePatient null;
  678.         $pcieDistinct $panierepo->getPcieDistinctByPatient($patient->getId(), $latitudePatient$longitudePatient);
  679.         $pharmacyIds $this->listIdPharmacie($pcieDistinct);
  680.         if (empty($pharmacyIds)) {
  681.             return new JsonResponse([
  682.                 'success' => 'Aucune pharmacie dans le panier',
  683.                 'dataAssurances' => []
  684.             ], Response::HTTP_OK);
  685.         }
  686.         // 1. Cartes du patient avec leur vrai % de prise en charge
  687.         $cartesMap $cateRepo->findAssuranceNumeroMapByUser($patient);
  688.         // Index rapide : numéro de carte → prise en charge
  689.         $numeroToPriseEnCharge = [];
  690.         foreach ($cartesMap as $info) {
  691.             $numeroToPriseEnCharge[$info['numero']] = $info['prisencharge'] ?? null;
  692.         }
  693.         // 2. Toutes les assurances acceptées par au moins une pharmacie du panier
  694.         $assurances $assuranceRepo->getDistinctByPharmacie($pharmacyIds);
  695.         $dataAssurances = [];
  696.         foreach ($assurances as $assurance) {
  697.             $myCartes = [];
  698.             // On parcourt TOUTES les cartes de cette assurance
  699.             foreach ($assurance->getCartes() as $carte) {
  700.                 $isPatientCarte = (
  701.                     $carte
  702.                     && $carte->getUser()
  703.                     && $carte->getUser()->getId() === $patient->getId()
  704.                 );
  705.                 // On affiche la carte SEULEMENT si elle appartient au patient
  706.                 if ($isPatientCarte) {
  707.                     $priseEnCharge $numeroToPriseEnCharge[$carte->getNumero()] ?? null;
  708.                     $myCartes[] = [
  709.                         'carteId'      => $carte->getId(),
  710.                         'userName'     => $carte->getUser()->getNomComplet(),
  711.                         'numero'       => $carte->getNumero(),
  712.                         'prisencharge' => $priseEnCharge,
  713.                     ];
  714.                 }
  715.             }
  716.             // On ajoute TOUJOURS l'assurance (même si $myCartes est vide)
  717.             $dataAssurances[] = [
  718.                 'assuranceId'  => $assurance->getId(),
  719.                 'designation'  => $assurance->getDesignation(),
  720.                 'adresse'      => $assurance->getAdresse() ?? '',
  721.                 'logo'         => $assurance->getLogo() ?? null,
  722.                 'cartes'       => $myCartes// [] si le patient n'a pas de carte ici
  723.                 //'hasCarte'     => !empty($myCartes), // Bonus : utile côté front
  724.             ];
  725.         }
  726.         return new JsonResponse([
  727.             'success'        => 'Informations récupérées avec succès',
  728.             'dataAssurances' => $dataAssurances
  729.         ], Response::HTTP_OK);
  730.     }
  731.     /**
  732.     * @param array $pcieDistinct
  733.     * @return int[]
  734.     */
  735.     private function listIdPharmacie(array $pcieDistinct): array
  736.     {
  737.         $ids = [];
  738.         foreach ($pcieDistinct as $pcie) {
  739.             // sécuriser la clé existante
  740.             if (isset($pcie['ictuspharmacie_id']) && is_numeric($pcie['ictuspharmacie_id'])) {
  741.                 $id = (int)$pcie['ictuspharmacie_id'];
  742.                 if (!in_array($id$idstrue)) {
  743.                     $ids[] = $id;
  744.                 }
  745.             }
  746.         }
  747.         return $ids;
  748.     }
  749.     /**
  750.      * @Route("/panier/addremise", name="app_panier_addremise")
  751.      */
  752.     public function addRemise(Request $requestRemiseUserPharmacieRepository $remiseUserPharmacieRepoRemiseService $remiseServiceIctusPharmacieRepository $ictusPharmacieRepo)
  753.     {
  754.         if ($request->isMethod('POST')) {
  755.             $user $this->getUser();
  756.             $remise = (int)$request->get('remise');
  757.             $pharmacie $ictusPharmacieRepo->find($request->get('pharmacie'));
  758.             if ($remise >= && $remise <= 100) {
  759.                 $remiseUserPharmacie $remiseUserPharmacieRepo->findOneBy(['user' => $user'pharmacie' => $pharmacie]);
  760.                 if ($remiseUserPharmacie) {
  761.                     $isValide null;
  762.                     if ($remise == $remiseUserPharmacie->getRemise()) {
  763.                         $isValide 1;
  764.                     }
  765.                     $remiseUserPharmacie->setRemise($remise)->setIsValide($isValide);
  766.                 } else {
  767.                     $remiseUserPharmacie = new RemiseUserPharmacie();
  768.                     $remiseUserPharmacie->setUser($user)
  769.                         ->setRemise($remise)
  770.                         ->setPharmacie($pharmacie)
  771.                         ->setIsValide(null)
  772.                         ->setCreatedAt(new \DateTimeImmutable());
  773.                 }
  774.                 $this->em->persist($remiseUserPharmacie);
  775.                 $this->em->flush();
  776.                 $remise = array(
  777.                     $pharmacie->getId() => $remise
  778.                 );
  779.                 $remiseService->add($remise);
  780.             }
  781.             return new JsonResponse("ok");
  782.         }
  783.     }
  784.     
  785.     private function getRemiseUser($user$remiseService$remiseUserPharmacieRepo)
  786.     {
  787.         $remiseUserPharmacie $remiseUserPharmacieRepo->findByUser($user);
  788.         if ($remiseUserPharmacie) {
  789.             foreach ($remiseUserPharmacie as $remUP) {
  790.                 $remise = array(
  791.                     $remUP->getPharmacie()->getId() => $remUP->getRemise()
  792.                 );
  793.                 $remiseService->add($remise);
  794.             }
  795.         }
  796.     }
  797.     
  798.     #[Route('/paiements-pcie/{id}'name'api_patient_ictus_panier_paiemens_pcie'methods: ['GET'])]
  799.     public function recuptypePaiementPcie(IctusPharmacie $ictusPcie): Response
  800.     {
  801.         if ($ictusPcie != null) {
  802.             $paimentsPcies $ictusPcie->getIctusPaiementPharmacies();
  803.             if (count($paimentsPcies) > 0) {
  804.                 $dataPaiements = [];
  805.                 foreach ($paimentsPcies as $paiement) {
  806.                     $dataPaiements[] = [
  807.                         'paiementID'  => $paiement->getIctusTypePaiement()->getId(),
  808.                         'designation' => $paiement->getIctusTypePaiement()->getDesignation()
  809.                     ];
  810.                 }
  811.                 return new JsonResponse([
  812.                     'success'           => 'Informations recuperées avec succès',
  813.                     'dataTypePaiements' => $dataPaiements
  814.                 ], Response::HTTP_OK);
  815.             }
  816.         }
  817.         return new JsonResponse(['error' => 'Pharmacie non trouvé'], Response::HTTP_NOT_FOUND);
  818.     }
  819.     #[Route('/somme-total/{id}'name'api_patient_ictus_panier_somme_total'methods: ['GET'])]
  820.     public function sommeTotal(User $userIctusPanierPatientRepository $panierRepo): Response
  821.     {
  822.         if ($user != null) {
  823.             $monPaniers $panierRepo->findBy(['user' => $user]);
  824.             if (count($monPaniers) > 0) {
  825.                 $sommePanier 0.0;
  826.                 foreach ($monPaniers as $p) {
  827.                     $sommePanier += ($p->getTotal());
  828.                 }
  829.                 return new JsonResponse([
  830.                     'success'           => 'Informations recuperées avec succès',
  831.                     'sommePanier' => $sommePanier
  832.                 ], Response::HTTP_OK);
  833.             }
  834.         }
  835.         return new JsonResponse(['error' => 'Utilisateur non trouvé'], Response::HTTP_NOT_FOUND);
  836.     }
  837.     //Step 3 dans paiement avant validation cmd
  838.     #[Route('/ajout-assurance'name'app_panier_add_assurance'methods: ['POST'])]
  839.     public function addAssurance(
  840.         Request $request,
  841.         EntityManagerInterface $em,
  842.         UserRepository $userRepo,
  843.         AssuranceRepository $assuranceRepo,
  844.         CarteRepository $carteRepo
  845.     ): Response {
  846.         $data json_decode($request->getContent(), true);
  847.         // Si JSON invalide ou vide
  848.         if (!$data || !is_array($data)) {
  849.             return new JsonResponse([
  850.                 'error' => true,
  851.                 'message' => 'Données JSON invalides'
  852.             ], Response::HTTP_BAD_REQUEST);
  853.         }
  854.         if (empty($data['userId']) || empty($data['assuranceId']) || !isset($data['numeroCarte'])) {
  855.             return new JsonResponse([
  856.                 'error' => true,
  857.                 'message' => 'userId, assuranceId et numeroCarte sont obligatoires'
  858.             ], Response::HTTP_BAD_REQUEST);
  859.         }
  860.         $user $userRepo->find($data['userId']);
  861.         $assurance $assuranceRepo->find($data['assuranceId']);
  862.         if (!$user) {
  863.             return new JsonResponse(['error' => true'message' => 'Utilisateur non trouvé'], 404);
  864.         }
  865.         if (!$assurance && $data['assuranceId'] == 0) {
  866.             return new JsonResponse(['error' => true'message' => 'Assurance non trouvée'], 404);
  867.         }
  868.         $carte $carteRepo->findOneBy(['user' => $user'assurance' => $assurance]);
  869.         if ($carte) {
  870.             // Mise à jour du numéro
  871.             $carte->setNumero((string)$data['numeroCarte']);
  872.         } else {
  873.             // Création nouvelle carte
  874.             $carte = new Carte();
  875.             $carte->setUser($user)
  876.                 ->setAssurance($assurance)
  877.                 ->setNumero((string)$data['numeroCarte']);
  878.         }
  879.         $em->persist($carte);
  880.         $em->flush();
  881.         return new JsonResponse([
  882.             'error' => false,
  883.             'message' => 'Carte sauvegardée avec succès',
  884.             'data' => [
  885.                 'assuranceId' => $assurance->getId(),
  886.                 'designation' => $assurance->getDesignation(),
  887.                 'numeroCarte' => $carte->getNumero()
  888.             ]
  889.         ], Response::HTTP_OK);
  890.     }
  891.     function getUserIpAddr()
  892.     {
  893.         if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
  894.             // IP address from shared internet
  895.             $ip $_SERVER['HTTP_CLIENT_IP'];
  896.         } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  897.             // IP address passed from proxy
  898.             $ip $_SERVER['HTTP_X_FORWARDED_FOR'];
  899.         } else {
  900.             // Regular IP address
  901.             $ip $_SERVER['REMOTE_ADDR'];
  902.         }
  903.         return $ip;
  904.     }
  905.     public function montantWithFrai($val)
  906.     {
  907.         $pourcentage 0;
  908.         switch (true) {
  909.             case ($val && $val <= 10000):
  910.                 $pourcentage 2;
  911.                 break;
  912.             case ($val 10000 && $val <= 20000):
  913.                 $pourcentage 1.75;
  914.                 break;
  915.             case ($val 20000 && $val <= 30000):
  916.                 $pourcentage 1.25;
  917.                 break;
  918.             case ($val 30000 && $val <= 50000):
  919.                 $pourcentage 1.5;
  920.                 break;
  921.             case ($val 50000 && $val <= 80000):
  922.                 $pourcentage 1.75;
  923.                 break;
  924.             case ($val 80000 && $val <= 120000):
  925.                 $pourcentage 1.5;
  926.                 break;
  927.             case ($val 120000 && $val <= 170000):
  928.                 $pourcentage 1.40;
  929.                 break;
  930.             case ($val 170000):
  931.                 $pourcentage 1.30;
  932.                 break;
  933.             default:
  934.                 $pourcentage 0;
  935.                 break;
  936.         }
  937.         return $val + ($val $pourcentage 100);
  938.     }
  939. }