src/V4Bundle/Controller/CommandApiV4Controller.php line 2312

Open in your IDE?
  1. <?php
  2. namespace App\V4Bundle\Controller;
  3. use App\Enums\AdditionnalFeeAmountType;
  4. use App\Enums\AdditionnalFeeType;
  5. use App\Enums\AdditionalFeeRuleType;
  6. use App\Entity\AdditionalFeeRule;
  7. use App\Entity\AdditionalFees;
  8. use App\Entity\Billing;
  9. use App\Entity\PaymentBill;
  10. use App\Entity\RestaurantConfig;
  11. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  12. use Symfony\Component\HttpFoundation\JsonResponse;
  13. use Symfony\Component\HttpFoundation\Response;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\Routing\Annotation\Route;
  16. use Doctrine\ORM\EntityManagerInterface;
  17. use App\Entity\Food;
  18. use App\Entity\Adresses;
  19. use App\V4Bundle\Entity\Billing2;
  20. use App\Entity\Client;
  21. use App\V4Bundle\Entity\ClientBalance;
  22. use App\Entity\Command;
  23. use App\Entity\DeliveryRating;
  24. use App\Entity\Livreur;
  25. use App\V4Bundle\Entity\Loyalty;
  26. use App\Entity\PackagingAdditionnalFeeBilling;
  27. use App\V4Bundle\Entity\PayBonus;
  28. use App\V4Bundle\Entity\PreOrderConfig;
  29. use App\Entity\PromotionSchedule;
  30. use App\Entity\RestoFraisSupp;
  31. use App\V4Bundle\Entity\Schedule;
  32. use App\Entity\Transaction;
  33. use App\Entity\Voucher;
  34. use App\V4Bundle\Entity\VoucherSubscription;
  35. use App\Entity\WeatherRule;
  36. use App\Entity\Zone;
  37. use App\Entity\ZoneResto;
  38. use DateTime;
  39. use Doctrine\Common\Cache\Cache;
  40. use Symfony\Component\Serializer\SerializerInterface;
  41. use App\V4Bundle\Controller\BaseController;
  42. use App\V4Bundle\Entity\DeliveryRating as EntityDeliveryRating;
  43. use App\V4Bundle\Entity\Devices;
  44. use App\V4Bundle\Entity\Employee;
  45. use App\V4Bundle\Entity\NewUserPromotion;
  46. use App\V4Bundle\Entity\Pack;
  47. use App\V4Bundle\Entity\PreorderCommandDetails;
  48. use App\V4Bundle\Entity\VoucherOwner;
  49. use App\V4Bundle\Entity\VoucherTransaction;
  50. use App\V4Bundle\Entity\VoucherUsage;
  51. use Symfony\Component\Mime\Address;
  52. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  53. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  54. use App\V4Bundle\Words\Words;
  55. use Doctrine\DBAL\Connection;
  56. use Exception;
  57. use Google\Service\SQLAdmin\Resource\Connect;
  58. use Symfony\Contracts\HttpClient\HttpClientInterface;
  59. use App\V4Bundle\Entity\Subscription;
  60. use App\V4Bundle\Entity\SharedUser;
  61. use App\V4Bundle\Entity\UserSusOrd;
  62. use PhpParser\Node\Expr\Throw_;
  63. use ProxyManager\Factory\RemoteObject\Adapter\JsonRpc;
  64. use Symfony\Component\Validator\Constraints\Json;
  65. use Throwable;
  66. class CommandApiV4Controller extends BaseController
  67. {
  68.     protected  $tokenStorage;
  69.     protected  $serializer;
  70.     protected  $entityManager;
  71.     protected  $passwordHasher;
  72.     protected $connection;
  73.     protected   $http_client;
  74.     public function __construct(
  75.         SerializerInterface $serializer,
  76.         EntityManagerInterface $entityManager,
  77.         UserPasswordHasherInterface $passwordHasher,
  78.         TokenStorageInterface $tokenStorage,
  79.         Connection $connection,
  80.         HttpClientInterface $http_client
  81.     ) {
  82.         $this->serializer $serializer;
  83.         $this->entityManager $entityManager;
  84.         $this->passwordHasher $passwordHasher;
  85.         $this->tokenStorage $tokenStorage;
  86.         $this->connection $connection;
  87.         $this->http_client $http_client;
  88.     }
  89.     /**
  90.      * @Route("mobile/api/command/billing/v5/get", name="user_mobile_v5_get_command_billing:", methods={"POST"})
  91.      */
  92.     public function getCommandBillingWithVoucherV5Action(Request $request)
  93.     {
  94.         $currentToken $this->get('security.token_storage')->getToken();
  95.         $user $currentToken->getUser();
  96.         $id $user->getId();
  97.         $data json_decode($request->getContent(), true);
  98.         if (
  99.             isset($data["restaurant_id"]) &&
  100.             isset($data["shipping_address"]) &&
  101.             $data["restaurant_id"] != null &&
  102.             $data["shipping_address"] != null &&
  103.             count($data["food_command"]) != 0
  104.         ) {
  105.             //check user's number of order so far 
  106.             $nb_order $this->checkNumberOfOrderFoUser($id); 
  107.             if($nb_order >= && $nb_order <= 5){
  108.                 $data['voucher_id']=null;
  109.                 $data['use_kaba_point']=false;
  110.             }
  111.             $restaurant $this->entityManager->getRepository(RestaurantConfig::class)->find(intval($data["restaurant_id"]));
  112.             $address =  $this->entityManager->getRepository(Adresses::class)->find(intval($data["shipping_address"]));
  113.             $configs_with_voucher $this->configsWithVoucher($data$currentToken$user$restaurant$address);
  114.             /*
  115.             try {
  116.                 $api_call = $this->http_client->request(
  117.                     'POST',
  118.                     'https://low-cod-36.deno.dev/relay',
  119.                     [
  120.                         'json' => ['userId' => $id],
  121.                         'headers' => [
  122.                             'Content-Type' => 'application/json',
  123.                             'User-Agent'  => 'PostmanRuntime/7.32.3'
  124.                         ],
  125.                         'timeout' => 10,
  126.                         'max_duration' => 10,
  127.                         'http_version' => '1.1',
  128.                     ]
  129.                 );
  130.             
  131.                 $res_api = $api_call->getContent(false); 
  132.                 $apiData = json_decode($res_api, true);
  133.                 if ($apiData) {
  134.                     $data['user_abonnement'] = $apiData;
  135.                 }
  136.             
  137.             } catch (\Throwable $e) {
  138.                 error_log("API proxy failed: ".$e->getMessage());
  139.                 $data['user_abonnement'] = null;
  140.             }
  141.             */
  142.             $res = [];
  143.             $res["promotion_pricing"] = $this->getPromotionPricing($data$configs_with_voucher);
  144.             $res["command_pricing"] = $this->calculate_command_pricing($data["food_command"]);
  145.             $res["account_balance"] = $this->getBalance($id);
  146.             $res["distance"] = $this->getDistance($restaurant->getLocation(), $address->getLocation());
  147.             $res["shipping_pricing"] = $this->calculate_shipping_price($res["distance"], $currentToken);
  148.             $res["kaba_point"] = $this->get_kaba_point($id$res['shipping_pricing']);
  149.             $res['is_new_user']=false;
  150.             $res["promotion_shipping_pricing"] = $this->getPromotionOnShipping($restaurant$data$address$currentToken$user$configs_with_voucher$res['shipping_pricing'], $res['kaba_point']);
  151.             //Subscription 
  152.             try{
  153.                 if(isset($data['user_abonnement']) &&$data['user_abonnement']!=null){
  154.                     $res["promotion_shipping_pricing"] = $this->applySubscriptionOnOrder($res['distance'], $data['user_abonnement'], $res['promotion_shipping_pricing']);
  155.                     $res['has_subscription'] =  $res["promotion_shipping_pricing"]==0?true:false;
  156.                 }
  157.             }catch(Throwable $e){}
  158.             if(!isset($data['user_abonnement'])){
  159.                 try{
  160.                     if($nb_order >= && $nb_order <= 5){
  161.                         $promotion $this->entityManager->getRepository(NewUserPromotion::class)->findAll();
  162.                         if($promotion){
  163.                             if($promotion[0]->getIsActive()==true){
  164.                                 $promotion_for_new_user $promotion[0] ->getValue();
  165.                                 $res["promotion_shipping_pricing"] = $res['shipping_pricing']-$promotion_for_new_user;
  166.                                 $res['is_new_user']=true;
  167.                             }else{
  168.                                
  169.                             }
  170.                         }
  171.                     }
  172.                 }catch(Throwable $e){}
  173.             }
  174.             $res['additional_fees'] = $this->getAdditionalFeesPrice($data['food_command'], $res['command_pricing'], $res['shipping_pricing'], $address$restaurant);
  175.             $res['additional_fees_total_price'] = $this->getAdditionalFeesTotalPricing($res["additional_fees"]);
  176.             $res["total_pricing"] = $this->get_total_pricing($res$configs_with_voucher$data$id$res["kaba_point"]);
  177.             $res['total_normal_pricing'] = intval($res["command_pricing"]) + intval($res["shipping_pricing"]) + intval($res['additional_fees_total_price']);
  178.             $res["remise"] = $this->get_remise($id$res$data$res["kaba_point"]);
  179.             $res["pay_at_delivery"] = $restaurant->getPayAtDelivery();
  180.             $res["prepayed"] = $restaurant->getPrepayed();
  181.             $res["trustful"] = $user->getTrustful();
  182.             $res["max_pay"] = intval($restaurant->getMaxPay());
  183.             $res["cooking_time"] = (int)$restaurant->getCookingTime();
  184.             $res['eligible_vouchers'] = $this->getUserEligibleVoucher($id);
  185.             $res["out_of_range"] = $this->isOutOfRange($res['distance']);
  186.             if(isset($data['user_abonnement'])){
  187.                 $res['subscription']= $data['user_abonnement'];
  188.             }
  189.             $additional_fee $this->entityManager->getRepository(AdditionalFees::class)->findOneBy(["fee_type" => AdditionnalFeeType::COMMISSION_FEE]);
  190.             try{
  191.                 $commission_additional_fee $this->entityManager->getRepository(RestoFraisSupp::class)->findOneBy(["resto_id" => $data['restaurant_id'], "additional_fee_id" => $additional_fee->getId()]);
  192.                 if($commission_additional_fee){
  193.                     $isEnabled =  $commission_additional_fee->isFeeEnabled();
  194.                 }
  195.             }catch(Throwable $e){
  196.                 $isEnabled false;
  197.             }
  198.             if ($isEnabled == true) {
  199.                 $sql 'SELECT * FROM devices WHERE id = :id';
  200.                 $device $this->connection->fetchAssociative($sql, ['id' => $user->getDeviceId()]);  
  201.                 $push_token $device['push_token'];
  202.                 try{
  203.                     $notif = [];
  204.                     $notif["error"] = 0;
  205.                     $notif["message"] = "nothing";
  206.                     $notif["data"] = [];
  207.                     $notif["data"]["notification"] = [];
  208.                     $notif["data"]["notification"]["title"] = "ℹ️ Frais supplémentaires";
  209.                     $notif["data"]["notification"]["body"] = "Des frais supplémentaires sont appliqués chez ce marchand";
  210.                     $notif["data"]["notification"]["image_link"] = '';
  211.                     $notif["data"]["notification"]["destination"] = [];
  212.                     $notif["data"]["notification"]["destination"]["type"] = 200;
  213.                     $notif["data"]["notification"]["destination"]["priority"] = 2;
  214.                     $notif["data"]["notification"]["destination"]["amount"] = intval(0);
  215.                     $notif["data"]["notification"]["destination"]["is_out_of_app"] = intval(0);
  216.                     $notif["data"]["notification"]["destination"]["product_id"] = intval(0);
  217.                   //  $this->sendNotificationToDeviceV2([$push_token],"Des frais supplémentaires sont appliqués chez ce marchand",$notif,1);
  218.                 }catch(Throwable $e){
  219.                 }
  220.             }
  221.             return new Response($this->serializer->serialize($this->okResponseBlob($res), 'json'));
  222.         } else {
  223.             return new Response($this->serializer->serialize($this->errorResponseBlob('Invalid parameter'), 'json'));
  224.         }
  225.     }
  226.         /**
  227.      * @Route("mobile/api/command/v5-old/create", name="mobile_api_command_v5_old_create", methods={"POST"})
  228.      */
  229.     public function createCommandWithVoucherV5OldAction(Request $request)
  230.     {
  231.         $currentToken $this->get('security.token_storage')->getToken();
  232.         $user $currentToken->getUser();
  233.         $id $user->getId();
  234.         $data json_decode($request->getContent(), true);
  235.         $saved_data json_decode($request->getContent(), true);
  236.         $is_preorder 0;
  237.         $is_voucher 0;
  238.         /*try {
  239.             $api_call = $this->http_client->request(
  240.                 'POST',
  241.                 'https://huge-bear-80.deno.dev/relay',
  242.                 [
  243.                     'json' => ['userId' => $id],
  244.                     'headers' => [
  245.                         'Content-Type' => 'application/json',
  246.                         'User-Agent'  => 'PostmanRuntime/7.32.3'
  247.                     ],
  248.                     'timeout' => 10,
  249.                     'max_duration' => 10,
  250.                     'http_version' => '1.1',
  251.                 ]
  252.             );
  253.         
  254.             $res_api = $api_call->getContent(false); 
  255.             $apiData = json_decode($res_api, true);
  256.             if ($apiData) {
  257.                 $saved_data['user_abonnement'] = $apiData;
  258.             }
  259.         
  260.         } catch (\Throwable $e) {
  261.             error_log("API proxy failed: ".$e->getMessage());
  262.             $saved_data['user_abonnement'] = null;
  263.         }
  264.         */
  265.            
  266.         //check user's number of order so far 
  267.        $nb_order $this->checkNumberOfOrderFoUser($id); 
  268.         if($nb_order >= && $nb_order <= 5){
  269.             $data['voucher_id']=null;
  270.             $data['use_kaba_point']=false;
  271.         }
  272.         $deliveryRange = [];
  273.         if (isset($data["pre_order"]) && $data["pre_order"] == && isset($data["pre_order_hour"]) && $data["pre_order_hour"] != null) {
  274.             $deliveryRange = array('start' => $data["pre_order_hour"]["start"], 'end' => $data["pre_order_hour"]["end"]);
  275.             $is_preorder 1;
  276.         }
  277.         $restaurantId $this->getRestaurantId($data["food_command"]);
  278.         $adress $this->getAdress($data["shipping_address"]);
  279.         if ($restaurantId == -1)
  280.             return new Response($this->serializer->serialize($this->errorResponseBlob(null301), 'json'));
  281.         if ($adress == -1)
  282.             return new Response($this->serializer->serialize($this->errorResponseBlob(null304), 'json'));
  283.         $voucher_id null;
  284.         if (isset($data["voucher_id"]) && $data["voucher_id"] != null) {
  285.             $voucher_id intval($data["voucher_id"]);
  286.             $is_voucher 1;
  287.         }
  288.         $use_kaba_point false;
  289.         if (isset($data["use_kaba_point"]) && $data["use_kaba_point"] != null)
  290.             $use_kaba_point $data["use_kaba_point"];
  291.         $command_details $this->getCommandDetails2($data["food_command"], $restaurantId$adress$is_preorder$voucher_id$id$use_kaba_point);
  292.         $data["food_command"] = $command_details["foods"];
  293.         $restaurant =  $this->entityManager->getRepository(RestaurantConfig::class)->find($restaurantId);
  294.         $details "Achat de " " " $command_details["food_litteral"] . " " "à" " " $restaurant->getName();
  295.         if (!($this->checkValidUser($id)))
  296.             return new Response($this->serializer->serialize($this->errorResponseBlob(null306), 'json'));
  297.         $master_key md5('kabapeur');
  298.         if (!(isset($data['master_key']) && $data['master_key'] == $master_key)) {
  299.             if (!($this->checkTransactionPassword($id$data["transaction_password"])))
  300.                 return new Response($this->serializer->serialize($this->errorResponseBlob(null300), 'json'));
  301.         }
  302.         $isFirstCommandBonusApply $this->isFirstCommandBonusApply($id);
  303.         if ($isFirstCommandBonusApply['response'] && $isFirstCommandBonusApply['type'] == '1') {
  304.             $haveBillingDiscount true;
  305.         } else {
  306.             $haveBillingDiscount $command_details["haveBillingDiscount"];
  307.         }
  308.         $client =  $this->entityManager->getRepository(Client::class)->find($id);
  309.         $command = new Command();
  310.         $em $this->entityManager;
  311.         $word false;
  312.         while ($word == false) {
  313.             $word $this->generateWord();
  314.         }
  315.         $command->setPassPhrase($word);
  316.         if ($command_details["is_kaba_point_used"]) {
  317.             $kabaPointTransaction $this->debitKabaPointAccount($idintval($command_details["kaba_point_used_amount"]));
  318.             if ($kabaPointTransaction['state']) {
  319.                 $command->setKabaPoint(intval($kabaPointTransaction["transaction"]["id"]));
  320.                 $command->setKabaPointAmount(intval($command_details["kaba_point_used_amount"]));
  321.             } else {
  322.                 $command_details["food_billing"] += intval($command_details["kaba_point_used_amount"]);
  323.                 $command_details["email_shipping_pricing"] += intval($command_details["kaba_point_used_amount"]);
  324.                 $command_details["phoneNumber_shipping_pricing"] += intval($command_details["kaba_point_used_amount"]);
  325.             }
  326.         }
  327.         $is_subscription_discount_allowed =false;
  328.         $realyShippingPrice $isFirstCommandBonusApply['response'] && $isFirstCommandBonusApply['type'] == '1' $command_details["food_billing"];
  329.         $command->setFoodCommand($data["food_command"]);
  330.         $command->setPreOrder($is_preorder);
  331.         $command->setPayAtDelivery($data["pay_at_delivery"]);
  332.         $command->setClientId($id);
  333.         $command->setClient($user);
  334.         $command->setState(-1);
  335.         $command->setRestaurantId($restaurantId);
  336.         $command->setRestaurant($restaurant);
  337.         $command->setShippingAddress($adress);
  338.         $command->setHaveBillingDiscount($haveBillingDiscount);
  339.         $command->setExtraShippingPricing($command_details["extra_shipping_pricing"] > $realyShippingPrice $command_details["extra_shipping_pricing"]);
  340.         $command->setBaseShippingPricing($command_details["base_shipping_pricing"]);
  341.         $command->setEmailAccountShippingPricing($command_details["email_shipping_pricing"]);
  342.         $command->setPhoneNumberAccountShippingPricing($command_details["phoneNumber_shipping_pricing"]);
  343.         $command->setShippingPricing($realyShippingPrice);
  344.         //Subscription 
  345.         try{
  346.             if(isset($saved_data['user_abonnement'])){
  347.                 $promotion_shipping_pricing $this->applySubscriptionOnOrder($this->getDistance($restaurant->getLocation(), $adress['location']),$saved_data['user_abonnement'],$command->getShippingPricing());
  348.                 if($promotion_shipping_pricing==0){
  349.                     $command->setHaveBillingDiscount(true);
  350.                     $is_subscription_discount_allowed true;
  351.                     $command->setShippingPricing(0);
  352.                 }else{
  353.                     $command->setHaveBillingDiscount(false);
  354.                 }
  355.             }
  356.         }catch(Throwable $e){
  357.             
  358.         }
  359.         if(!isset($saved_data['user_abonnement'])){
  360.             try{
  361.                 if($nb_order >= && $nb_order <= 5){
  362.                     $promotion $this->entityManager->getRepository(NewUserPromotion::class)->findAll();
  363.                     if($promotion){
  364.                         if($promotion[0] ->getIsActive()==true){
  365.                             $promotion_for_new_user $promotion[0] ->getValue();
  366.                             $command->setHaveBillingDiscount(true);
  367.                             $command->setShippingPricing($realyShippingPrice-$promotion_for_new_user);
  368.                          }
  369.                     }
  370.                 }
  371.             }catch(Throwable $e){
  372.                 
  373.             }
  374.         }
  375.         $command->setStartTime(date('Y-m-d H:i:s'));
  376.         $command->setStartDate(date('Y-m-d'));
  377.         $command->setLastUpdate(date('Y-m-d H:i:s'));
  378.         $client_commands $this->entityManager->getRepository(Command::class)->findBy([
  379.             'clientId' => $id,
  380.         ]);
  381.         if (count($client_commands) > 0)
  382.             $command->setIsFirstOrder(false);
  383.         else
  384.             $command->setIsFirstOrder(true);
  385.         if ($command_details['is_voucher_used'])
  386.             $command->setHasVoucher(true);
  387.         else
  388.             $command->setHasVoucher(false);
  389.         if (isset($data["infos"]) && $data["infos"] != null)
  390.             $command->setInfos($data["infos"]);
  391.             $now = new \DateTime();
  392.             $twoMinutesAgo = (clone $now)->modify('-2 minute');
  393.             $qb $this->entityManager->getRepository(Command::class)->createQueryBuilder('c')
  394.                 ->where('c.clientId = :clientId')
  395.                 ->andWhere('c.restaurantId = :restaurantId')
  396.                 ->andWhere(is_array($data['food_command']) 
  397.                     ? 'c.foodCommand IN (:foodCommand)' 
  398.                     'c.foodCommand = :foodCommand'
  399.                 )
  400.                 ->andWhere('c.startTime BETWEEN :start AND :now')
  401.                 ->setParameter('clientId'$id)
  402.                 ->setParameter('restaurantId'$restaurantId)
  403.                 ->setParameter('foodCommand'$data['food_command'])
  404.                 ->setParameter('start'$twoMinutesAgo->format('Y-m-d H:i:s'))
  405.                 ->setParameter('now'$now->format('Y-m-d H:i:s'));
  406.             
  407.             $existingCommand $qb->getQuery()->getOneOrNullResult();
  408.             
  409.                 if ($existingCommand) { 
  410.                     $jsonData json_encode([
  411.                                 "food_command" => $command->getFoodCommand(),
  412.                                 "restaurant_id" => $restaurant->getId(),
  413.                                 "shipping_address" => $adress['id'],
  414.                                 "voucher_id" => $voucher_id,
  415.                                 "use_kaba_point" => $use_kaba_point,
  416.                             ]);
  417.                             $Billingrequest = new Request(
  418.                                 [],
  419.                                 [],
  420.                                 [],
  421.                                 [],
  422.                                 [],
  423.                                 ['CONTENT_TYPE' => 'application/json'],
  424.                                 $jsonData
  425.                             );
  426.                             $getBilling $this->getCommandBillingWithVoucherAction($Billingrequest);
  427.                             $getBillingContent $getBilling->getContent();
  428.                             $getBillingData json_decode($getBillingContenttrue);
  429.                             $this->createPaymentBill($getBillingData['data'], $command->getId());
  430.                             return new JsonResponse($getBillingData200);
  431.                     }
  432.         $em->persist($command);
  433.         $em->flush();
  434.         if($is_subscription_discount_allowed==true){
  435.             $command_details["with_promo"]["total"] = $command_details["with_promo"]["total"]-$realyShippingPrice;
  436.             $command_details["with_promo"]["billing"] = 0;
  437.             $command_details["without_promo"]["pre_order"]["total"] =$command_details["without_promo"]["pre_order"]["total"] -$realyShippingPrice;
  438.             $command_details["without_promo"]["pre_order"]["billing"] = 0;
  439.         }
  440.         if ($data["device"]["push_token"] != null) {
  441.             $device =  $this->entityManager->getRepository(Devices::class)->findOneBy([
  442.                 'pushToken' => $data["device"]["push_token"]
  443.             ]);
  444.             if ($device != null) {
  445.                 $client->setDeviceId($device->getId());
  446.             } else {
  447.                 $device_id $this->createDevice($data["device"], 1);
  448.                 $client->setDeviceId($device_id);
  449.             }
  450.         }
  451.         $temp_foodPricing 0;
  452.         $tem_shippingPricing 0;
  453.         
  454.         if ($data["pay_at_delivery"] == true) {
  455.             if ($this->restaurantAcceptPayAtArrival($restaurantId)) {
  456.                 if ($command_details['is_voucher_used'] && $is_subscription_discount_allowed==false) {
  457.                     $pay_at_delivery_total_price intval($command_details["voucher_pricing"]["total_pricing"]);
  458.                     if ($isFirstCommandBonusApply['response']) {
  459.                         $pay_at_delivery_total_price -= intval($command_details["voucher_pricing"]["shipping_pricing"]);
  460.                         $temp_foodPricing $pay_at_delivery_total_price;
  461.                         $tem_shippingPricing intval($command_details["voucher_pricing"]["shipping_pricing"]);
  462.                     }
  463.                 } else {
  464.                     $pay_at_delivery_total_price intval($command_details["with_promo"]["total"]);
  465.                     if ($isFirstCommandBonusApply['response']) {
  466.                         $pay_at_delivery_total_price -= intval($command_details["with_promo"]["billing"]);
  467.                         $temp_foodPricing $pay_at_delivery_total_price;
  468.                         $tem_shippingPricing intval($command_details["with_promo"]["billing"]);
  469.                     }
  470.                 }
  471.                 $res $this->debitClientAction($id$pay_at_delivery_total_price$details0$command->getId());
  472.                 if ($res) {
  473.                     $command->setState(0);
  474.                     $em->flush();
  475.                     $isFirstCommandBonusApply['response'] ? $this->applyFirstCommandProccess($id$command->getId(), $temp_foodPricing$tem_shippingPricing) : '';
  476.                 } else {
  477.                     $em->remove($command);
  478.                     $em->flush();
  479.                 }
  480.             } else {
  481.                 $em->remove($command);
  482.                 $em->flush();
  483.                 return new Response($this->serializer->serialize($this->errorResponseBlob(null305), 'json'));
  484.             }
  485.         } else if ($data["pay_at_delivery"] == false) { // PREPAY
  486.             if (!$this->restaurantAcceptPrepay($restaurantId)) {
  487.                 $em->remove($command);
  488.                 $em->flush();
  489.                 return new Response($this->serializer->serialize(
  490.                     $this->errorResponseBlob(null308),
  491.                     'json'
  492.                 ));
  493.             }
  494.         
  495.             // =========================
  496.             // ===== PRE ORDER =========
  497.             // =========================
  498.             if ($is_preorder == 1) {
  499.         
  500.                 if (!$this->restaurantAcceptPreOrder($restaurantId$deliveryRange)) {
  501.                     $em->remove($command);
  502.                     $em->flush();
  503.                     return new Response($this->serializer->serialize(
  504.                         $this->errorResponseBlob(null307),
  505.                         'json'
  506.                     ));
  507.                 }
  508.         
  509.                 // 🔥 TOTAL DÉJÀ FINAL
  510.                 $preorderTotalPrice $command_details['is_voucher_used']
  511.                     ? intval($command_details["voucher_pricing"]["total_pricing"])
  512.                     : intval($command_details["without_promo"]["pre_order"]["total"]);
  513.         
  514.                 // 🎁 FIRST COMMAND BONUS (shipping déjà à 0 si subscription)
  515.                 if ($isFirstCommandBonusApply['response']) {
  516.         
  517.                     if ($command_details['is_voucher_used']) {
  518.                         $tem_shippingPricing intval($command_details["voucher_pricing"]["shipping_pricing"]);
  519.                     } else {
  520.                         $tem_shippingPricing intval($command_details["without_promo"]["pre_order"]["billing"]);
  521.                     }
  522.         
  523.                     $preorderTotalPrice -= $tem_shippingPricing;
  524.                     $temp_foodPricing $preorderTotalPrice;
  525.                 }
  526.         
  527.                 // 💳 DEBIT
  528.                 if ($this->debitClientAction($id$preorderTotalPrice$details1$command->getId())) {
  529.         
  530.                     $command->setState(0);
  531.                     $em->flush();
  532.         
  533.                     if ($isFirstCommandBonusApply['response']) {
  534.                         $this->applyFirstCommandProccess(
  535.                             $id,
  536.                             $command->getId(),
  537.                             $temp_foodPricing,
  538.                             $tem_shippingPricing
  539.                         );
  540.                     }
  541.         
  542.                 } else {
  543.         
  544.                     $em->remove($command);
  545.                     $em->flush();
  546.         
  547.                     return new Response($this->serializer->serialize(
  548.                         $this->errorResponseBlob(null305),
  549.                         'json'
  550.                     ));
  551.                 }
  552.         
  553.             // =========================
  554.             // ===== NORMAL ORDER ======
  555.             // =========================
  556.             } else {
  557.         
  558.                 // 🔥 TOTAL DÉJÀ FINAL
  559.                 $orderTotalPrice $command_details['is_voucher_used']
  560.                     ? intval($command_details["voucher_pricing"]["total_pricing"])
  561.                     : intval($command_details["with_promo"]["total"]);
  562.         
  563.                 // 🎁 FIRST COMMAND BONUS (shipping déjà à 0 si subscription)
  564.                 if ($isFirstCommandBonusApply['response']) {
  565.         
  566.                     if ($command_details['is_voucher_used']) {
  567.                         $tem_shippingPricing intval($command_details["voucher_pricing"]["shipping_pricing"]);
  568.                     } else {
  569.                         $tem_shippingPricing intval($command_details["with_promo"]["billing"]);
  570.                     }
  571.         
  572.                     $orderTotalPrice -= $tem_shippingPricing;
  573.                     $temp_foodPricing $orderTotalPrice;
  574.                 }
  575.         
  576.                 // 💳 DEBIT
  577.                 if ($this->debitClientAction($id$orderTotalPrice$details1$command->getId())) {
  578.         
  579.                     $command->setState(0);
  580.                     $em->flush();
  581.         
  582.                     if ($isFirstCommandBonusApply['response']) {
  583.                         $this->applyFirstCommandProccess(
  584.                             $id,
  585.                             $command->getId(),
  586.                             $temp_foodPricing,
  587.                             $tem_shippingPricing
  588.                         );
  589.                     }
  590.         
  591.                 } else {
  592.         
  593.                     // ===== MASTER KEY FALLBACK =====
  594.                     if (isset($data['master_key']) && $data['master_key'] == $master_key) {
  595.         
  596.                         if ($client->getTrustful() == || $this->isEmailAccount($client)) {
  597.                             $em->remove($command);
  598.                             $em->flush();
  599.                             return new Response($this->serializer->serialize(
  600.                                 $this->errorResponseBlob(null309),
  601.                                 'json'
  602.                             ));
  603.                         }
  604.         
  605.                         $_res $this->debitClientAction(
  606.                             $id,
  607.                             $orderTotalPrice,
  608.                             $details,
  609.                             0,
  610.                             $command->getId()
  611.                         );
  612.         
  613.                         if ($_res) {
  614.         
  615.                             $command->setState(0);
  616.                             $command->setPayAtDelivery(true);
  617.                             $em->flush();
  618.         
  619.                             if ($isFirstCommandBonusApply['response']) {
  620.                                 $this->applyFirstCommandProccess(
  621.                                     $id,
  622.                                     $command->getId(),
  623.                                     $temp_foodPricing,
  624.                                     $tem_shippingPricing
  625.                                 );
  626.                             }
  627.         
  628.                         } else {
  629.         
  630.                             $em->remove($command);
  631.                             $em->flush();
  632.         
  633.                             return new Response($this->serializer->serialize(
  634.                                 $this->errorResponseBlob(null308),
  635.                                 'json'
  636.                             ));
  637.                         }
  638.         
  639.                     } else {
  640.         
  641.                         $em->remove($command);
  642.                         $em->flush();
  643.         
  644.                         return new Response($this->serializer->serialize(
  645.                             $this->errorResponseBlob(null308),
  646.                             'json'
  647.                         ));
  648.                     }
  649.                 }
  650.             }
  651.         }
  652.         
  653.         if ($is_preorder == 1) {
  654.             $preorder_detail = new PreorderCommandDetails();
  655.             $preorder_detail->setCommandId($command->getId());
  656.             $preorder_detail->setStart($deliveryRange["start"]);
  657.             $preorder_detail->setEnd($deliveryRange["end"]);
  658.             $preorder_detail->setDiscount($command_details["discount"]);
  659.             $preorder_detail->setPrepayed(1);
  660.             $preorder_detail->setCreatedAt(strtotime(date("Y-m-d H:i:s")));
  661.             $em->persist($preorder_detail);
  662.             $em->flush();
  663.         }
  664.         if ($is_voucher == && ($command_details["voucher_pricing"]["valid"] == true || $command_details["is_voucher_used"])) {
  665.             $voucher_id intval($data["voucher_id"]);
  666.             $voucher $this->entityManager->getRepository(Voucher::class)->find($voucher_id);
  667.             $voucher_subs =  $this->entityManager->getRepository(VoucherSubscription::class)->findOneBy([
  668.                 'userId' => $id,
  669.                 'voucherId' => $voucher_id,
  670.             ]);
  671.             if ($voucher_subs != null) {
  672.                 $usage_count count($this->entityManager->getRepository(VoucherUsage::class)->findBy([
  673.                     'userId' => $id,
  674.                     'voucherId' => $voucher_id,
  675.                     'isReallyUsed' => 1
  676.                 ]));
  677.                 if ($voucher != null) {
  678.                     if (($usage_count 1) >= intval($voucher->getUseCount())) {
  679.                         $voucher_subs->setState(1);
  680.                     }
  681.                     $voucher_subs->setUseCount($usage_count 1);
  682.                     $new_usage = new VoucherUsage();
  683.                     $new_usage->setUserId($id);
  684.                     $new_usage->setVoucherId($voucher_id);
  685.                     $new_usage->setCommandId($command->getId());
  686.                     $new_usage->setIsReallyUsed(1);
  687.                     $new_usage->setCreatedAt(strtotime(date('Y-m-d H:i:s')));
  688.                     $em->persist($new_usage);
  689.                     $reward 0;
  690.                     $check_voucher_owners $this->entityManager->getRepository(VoucherOwner::class)->findBy([
  691.                         'voucherId' => $voucher_id
  692.                     ]);
  693.                     if ($check_voucher_owners != null) {
  694.                         if ($command_details["voucher_pricing"]["owner"]["is_rewarded"] == 1) {
  695.                             if ($command_details["voucher_pricing"]["owner"]["reward_on_food"] == 0) {
  696.                                 $reward $command_details["voucher_pricing"]["owner"]["reward_cash_value"];
  697.                             } else {
  698.                                 $reward $command_details["voucher_pricing"]["owner"]["reward_on_food"] + $command_details["voucher_pricing"]["owner"]["reward_on_billing"];
  699.                             }
  700.                         }
  701.                         if ($reward 0) {
  702.                             foreach ($check_voucher_owners as $owner) {
  703.                                 $voucher_transaction = new VoucherTransaction();
  704.                                 $voucher_transaction->setUserId($owner->getUserId());
  705.                                 $voucher_transaction->setVoucherId($voucher_id);
  706.                                 $voucher_transaction->setValue($reward);
  707.                                 $voucher_transaction->setType(1);
  708.                                 $voucher_transaction->setCommandId($command->getId());
  709.                                 $voucher_transaction->setState(0);
  710.                                 $voucher_transaction->setCreatedAt(strtotime(date('Y-m-d H:i:s')));
  711.                                 $voucher_transaction->setUpdatedAt(strtotime(date('Y-m-d H:i:s')));
  712.                                 $em->persist($voucher_transaction);
  713.                             }
  714.                         }
  715.                     }
  716.                 }
  717.             }
  718.             $em->flush();
  719.         }
  720.  
  721.         if ($restaurant->getDeviceId() != null) {
  722.             $device $this->entityManager->getRepository(Devices::class)->find($restaurant->getDeviceId());
  723.             if ($device != null && $device->getPushToken() != '') {
  724.                 $devices_array = [];
  725.                 array_push($devices_array$device->getPushToken());
  726.                 $devices_resto =[];
  727.                 $devices_resto = [];
  728.                 $device_resto $this->entityManager->getRepository(Devices::class)->find($restaurant->getDeviceId());
  729.                if ($device_resto != null && $device_resto->getPushToken() != null
  730.                      array_push($devices_resto$device_resto->getPushToken());
  731.              
  732.                 $notif = [];
  733.                 $notif["error"] = 0;
  734.                 $notif["message"] = "nothing";
  735.                 $notif["data"] = [];
  736.                 $notif["data"]["notification"] = [];
  737.                 $notif["data"]["notification"]["title"] = "Kaba";
  738.                 $notif["data"]["notification"]["body"] = "Vous avez une nouvelle commande !";
  739.                 $notif["data"]["notification"]["image_link"] = '';
  740.                 $notif["data"]["notification"]["destination"] = [];
  741.                 $notif["data"]["notification"]["destination"]["type"] = 154;
  742.                 $notif["data"]["notification"]["destination"]["priority"] = 300;
  743.                 $notif["data"]["notification"]["destination"]["product_id"] = intval($command->getId());
  744.                 $notif["data"]["notification"]["destination"]["is_out_of_app"] = intval(0);
  745.             
  746.                 try {
  747.                     $this->sendNotificationToDeviceV2($devices_resto"Vous avez une nouvelle commande !"$notif2);
  748.                 } catch (\Throwable $e) {
  749.                 }
  750.                 
  751.             }
  752.         }
  753.         $jsonData json_encode([
  754.             "food_command" => $command->getFoodCommand(),
  755.             "restaurant_id" => $restaurant->getId(),
  756.             "shipping_address" => $adress['id'],
  757.             "voucher_id" => $voucher_id,
  758.             "use_kaba_point" => $use_kaba_point,
  759.         ]);
  760.         $Billingrequest = new Request(
  761.             [],
  762.             [],
  763.             [],
  764.             [],
  765.             [],
  766.             ['CONTENT_TYPE' => 'application/json'],
  767.             $jsonData
  768.         );
  769.         $getBilling $this->getCommandBillingWithVoucherAction($Billingrequest);
  770.         $getBillingContent $getBilling->getContent();
  771.         $getBillingData json_decode($getBillingContenttrue);
  772.         $this->createPaymentBill($getBillingData['data'], $command->getId());
  773.         $client_balance $this->getBalance($id);
  774.         $data = [];
  775.         $data["balance"] = $client_balance;
  776.         $data["pre_order"] = $is_preorder;
  777.         $data["pre_order_hour"] = $deliveryRange;
  778.         $data["voucher_data"] = $command_details["voucher_pricing"];
  779.         $response["error"] = 0;
  780.         $response["code"] = 200;
  781.         $response["message"] = "200 OK";
  782.         $response["data"] = $data;
  783.         $pusher $this->getPusher();
  784.         $message = [];
  785.         $message['id'] = $command->getId();
  786.         $message['state'] = $command->getState();
  787.         $pusher->trigger($this->getParameter('PUSHER_APP_CHANNEL'), BaseController::NEW_COMMAND$message);
  788.         $sql 'SELECT * FROM devices WHERE id = :id';
  789.         $device $this->connection->fetchAssociative($sql, ['id' => $user->getDeviceId()]);  
  790.     
  791.         return new Response($this->serializer->serialize($this->okResponseBlob(['command_id'=>$command->getId(),'total_price'=>$command_details["with_promo"]["total"]]), 'json'));
  792.     }
  793.     /**
  794.      * @Route("mobile/api/command/v5/create", name="mobile_api_command_v5_create", methods={"POST"})
  795.      */
  796.     public function createCommandWithVoucherV5Action(Request $request)
  797.     {
  798.         $currentToken $this->get('security.token_storage')->getToken();
  799.         $user $currentToken->getUser();
  800.         $id $user->getId();
  801.         $data json_decode($request->getContent(), true);
  802.         $saved_data json_decode($request->getContent(), true);
  803.         $is_preorder 0;
  804.         $is_voucher 0;
  805.         /*
  806.            if (
  807.             !empty($data['user_abonnement']) &&
  808.             !empty($data['user_abonnement']['pack']) &&
  809.             !empty($data['user_abonnement']['pack']['id'])
  810.         ) {
  811.             try {
  812.                 $api_call = $this->http_client->request(
  813.                     'POST',
  814.                     'https://low-cod-36.deno.dev/relay',
  815.                     [
  816.                         'json' => ['userId' => $id],
  817.                         'headers' => [
  818.                             'Content-Type' => 'application/json',
  819.                             'User-Agent'  => 'PostmanRuntime/7.32.3'
  820.                         ],
  821.                         'timeout' => 10,
  822.                         'max_duration' => 10,
  823.                         'http_version' => '1.1',
  824.                     ]
  825.                 );
  826.         
  827.                 $res_api = $api_call->getContent(false); 
  828.                 $apiData = json_decode($res_api, true);
  829.         
  830.                 if ($apiData) {
  831.                     $saved_data['user_abonnement'] = $apiData;
  832.                 }
  833.         
  834.             } catch (\Throwable $e) {
  835.                 error_log("API proxy failed: ".$e->getMessage());
  836.                 $saved_data['user_abonnement'] = null;
  837.             }
  838.         }
  839.         */
  840.        //check user's number of order so far 
  841.        $nb_order $this->checkNumberOfOrderFoUser($id); 
  842.         if($nb_order >= && $nb_order <= 5){
  843.             $data['voucher_id']=null;
  844.             $data['use_kaba_point']=false;
  845.         }
  846.         $deliveryRange = [];
  847.         if (isset($data["pre_order"]) && $data["pre_order"] == && isset($data["pre_order_hour"]) && $data["pre_order_hour"] != null) {
  848.             $deliveryRange = array('start' => $data["pre_order_hour"]["start"], 'end' => $data["pre_order_hour"]["end"]);
  849.             $is_preorder 1;
  850.         }
  851.         $restaurantId $this->getRestaurantId($data["food_command"]);
  852.         $adress $this->getAdress($data["shipping_address"]);
  853.         if ($restaurantId == -1)
  854.             return new Response($this->serializer->serialize($this->errorResponseBlob(null301), 'json'));
  855.         if ($adress == -1)
  856.             return new Response($this->serializer->serialize($this->errorResponseBlob(null304), 'json'));
  857.         $voucher_id null;
  858.         if (isset($data["voucher_id"]) && $data["voucher_id"] != null) {
  859.             $voucher_id intval($data["voucher_id"]);
  860.             $is_voucher 1;
  861.         }
  862.         $use_kaba_point false;
  863.         if (isset($data["use_kaba_point"]) && $data["use_kaba_point"] != null)
  864.             $use_kaba_point $data["use_kaba_point"];
  865.         $command_details $this->getCommandDetails2($data["food_command"], $restaurantId$adress$is_preorder$voucher_id$id$use_kaba_point);
  866.         $data["food_command"] = $command_details["foods"];
  867.         $restaurant =  $this->entityManager->getRepository(RestaurantConfig::class)->find($restaurantId);
  868.         $details "Achat de " " " $command_details["food_litteral"] . " " "à" " " $restaurant->getName();
  869.         if (!($this->checkValidUser($id)))
  870.             return new Response($this->serializer->serialize($this->errorResponseBlob(null306), 'json'));
  871.         $master_key md5('kabapeur');
  872.         if (!(isset($data['master_key']) && $data['master_key'] == $master_key)) {
  873.             if (!($this->checkTransactionPassword($id$data["transaction_password"])))
  874.                 return new Response($this->serializer->serialize($this->errorResponseBlob(null300), 'json'));
  875.         }
  876.         $isFirstCommandBonusApply $this->isFirstCommandBonusApply($id);
  877.         if ($isFirstCommandBonusApply['response'] && $isFirstCommandBonusApply['type'] == '1') {
  878.             $haveBillingDiscount true;
  879.         } else {
  880.             $haveBillingDiscount $command_details["haveBillingDiscount"];
  881.         }
  882.         $client =  $this->entityManager->getRepository(Client::class)->find($id);
  883.         $command = new Command();
  884.         $em $this->entityManager;
  885.         $word false;
  886.         while ($word == false) {
  887.             $word $this->generateWord();
  888.         }
  889.         $command->setPassPhrase($word);
  890.         if ($command_details["is_kaba_point_used"]) {
  891.             $kabaPointTransaction $this->debitKabaPointAccount($idintval($command_details["kaba_point_used_amount"]));
  892.             if ($kabaPointTransaction['state']) {
  893.                 $command->setKabaPoint(intval($kabaPointTransaction["transaction"]["id"]));
  894.                 $command->setKabaPointAmount(intval($command_details["kaba_point_used_amount"]));
  895.             } else {
  896.                 $command_details["food_billing"] += intval($command_details["kaba_point_used_amount"]);
  897.                 $command_details["email_shipping_pricing"] += intval($command_details["kaba_point_used_amount"]);
  898.                 $command_details["phoneNumber_shipping_pricing"] += intval($command_details["kaba_point_used_amount"]);
  899.             }
  900.         }
  901.         $is_subscription_discount_allowed =false;
  902.         $realyShippingPrice $isFirstCommandBonusApply['response'] && $isFirstCommandBonusApply['type'] == '1' $command_details["food_billing"];
  903.         $command->setFoodCommand($data["food_command"]);
  904.         $command->setPreOrder($is_preorder);
  905.         $command->setPayAtDelivery($data["pay_at_delivery"]);
  906.         $command->setClientId($id);
  907.         $command->setClient($user);
  908.         $command->setState(-1);
  909.         $command->setRestaurantId($restaurantId);
  910.         $command->setRestaurant($restaurant);
  911.         $command->setShippingAddress($adress);
  912.         $command->setHaveBillingDiscount($haveBillingDiscount);
  913.         $command->setExtraShippingPricing($command_details["extra_shipping_pricing"] > $realyShippingPrice $command_details["extra_shipping_pricing"]);
  914.         $command->setBaseShippingPricing($command_details["base_shipping_pricing"]);
  915.         $command->setEmailAccountShippingPricing($command_details["email_shipping_pricing"]);
  916.         $command->setPhoneNumberAccountShippingPricing($command_details["phoneNumber_shipping_pricing"]);
  917.         $command->setShippingPricing($realyShippingPrice);
  918.         if (isset($data["infos"]) && $data["infos"] != null)
  919.         $command->setInfos($data["infos"]);
  920.         //Subscription 
  921.         try{
  922.             if(isset($saved_data['user_abonnement']) && $saved_data['user_abonnement']!=null){
  923.                 $promotion_shipping_pricing $this->applySubscriptionOnOrder($this->getDistance($restaurant->getLocation(), $adress['location']),$saved_data['user_abonnement'],$command->getShippingPricing());
  924.                 if($promotion_shipping_pricing==0){
  925.                     $command->setHaveBillingDiscount(true);
  926.                     $is_subscription_discount_allowed true;
  927.                     $command->setShippingPricing(0);
  928.                 }else{
  929.                     $command->setHaveBillingDiscount(false);
  930.                 }
  931.             }
  932.         }catch(Throwable $e){
  933.             error_log($e->getMessage());
  934.             error_log($e->getTraceAsString());
  935.         }
  936.         if(!isset($saved_data['user_abonnement'])){
  937.             try{
  938.                 if($nb_order >= && $nb_order <= 5){
  939.                     $promotion $this->entityManager->getRepository(NewUserPromotion::class)->findAll();
  940.                     if($promotion){
  941.                         if($promotion[0] ->getIsActive()==true){
  942.                             $promotion_for_new_user $promotion[0] ->getValue();
  943.                             $command->setHaveBillingDiscount(true);
  944.                             $command->setShippingPricing($realyShippingPrice-$promotion_for_new_user);
  945.                          }
  946.                     }
  947.                 }
  948.             }catch(Throwable $e){
  949.                 error_log($e->getMessage());
  950.                 error_log($e->getTraceAsString());
  951.             }
  952.         }
  953.         $command->setStartTime(date('Y-m-d H:i:s'));
  954.         $command->setStartDate(date('Y-m-d'));
  955.         $command->setLastUpdate(date('Y-m-d H:i:s'));
  956.         $client_commands $this->entityManager->getRepository(Command::class)->findBy([
  957.             'clientId' => $id,
  958.         ]);
  959.         if (count($client_commands) > 0)
  960.             $command->setIsFirstOrder(false);
  961.         else
  962.             $command->setIsFirstOrder(true);
  963.         if ($command_details['is_voucher_used'])
  964.             $command->setHasVoucher(true);
  965.         else
  966.             $command->setHasVoucher(false);
  967.        if($restaurant){
  968.          if($restaurant->getAutoAccept()==true){
  969.             $command->setIsAutoOrder(true);
  970.          }
  971.         }
  972.         $em->persist($command);
  973.         $em->flush();
  974.         try{
  975.             if ($data["device"]["push_token"] != null) {
  976.                 $device =  $this->entityManager->getRepository(Devices::class)->findOneBy([
  977.                     'pushToken' => $data["device"]["push_token"]
  978.                 ]);
  979.                 if ($device != null) {
  980.                     $client->setDeviceId($device->getId());
  981.                 } else {
  982.                     $device_id $this->createDevice($data["device"], 1);
  983.                     $client->setDeviceId($device_id);
  984.                 }
  985.             }
  986.             $temp_foodPricing 0;
  987.             $tem_shippingPricing 0;
  988.             if ($data["pay_at_delivery"] == true) {
  989.                 if ($this->restaurantAcceptPayAtArrival($restaurantId)) {
  990.                     if ($command_details['is_voucher_used'] && $is_subscription_discount_allowed==false) {
  991.                         $pay_at_delivery_total_price intval($command_details["voucher_pricing"]["total_pricing"]);
  992.                         if ($isFirstCommandBonusApply['response']) {
  993.                             $pay_at_delivery_total_price -= intval($command_details["voucher_pricing"]["shipping_pricing"]);
  994.                             $temp_foodPricing $pay_at_delivery_total_price;
  995.                             $tem_shippingPricing intval($command_details["voucher_pricing"]["shipping_pricing"]);
  996.                         }
  997.                     } else {
  998.                         $pay_at_delivery_total_price intval($command_details["with_promo"]["total"]);
  999.                         if ($isFirstCommandBonusApply['response']) {
  1000.                             $pay_at_delivery_total_price -= intval($command_details["with_promo"]["billing"]);
  1001.                             $temp_foodPricing $pay_at_delivery_total_price;
  1002.                             $tem_shippingPricing intval($command_details["with_promo"]["billing"]);
  1003.                         }
  1004.                     }
  1005.     
  1006.                     $res $this->debitClientAction($id$pay_at_delivery_total_price$details0$command->getId());
  1007.     
  1008.                     if ($res) {
  1009.                         $command->setState(0);
  1010.                         $em->flush();
  1011.                         $isFirstCommandBonusApply['response'] ? $this->applyFirstCommandProccess($id$command->getId(), $temp_foodPricing$tem_shippingPricing) : '';
  1012.                     } else {
  1013.                         $em->remove($command);
  1014.                         $em->flush();
  1015.                     }
  1016.                 } else {
  1017.                     $em->remove($command);
  1018.                     $em->flush();
  1019.                     return new Response($this->serializer->serialize($this->errorResponseBlob(null305), 'json'));
  1020.                 }
  1021.             }
  1022.              else if ($data["pay_at_delivery"] == false) { // PREPAY
  1023.                 if ($is_subscription_discount_allowed) {
  1024.                     if (isset($command_details['with_promo'])) {
  1025.                         $command_details['with_promo']['billing'] = 0;
  1026.                         $command_details['with_promo']['total'] =
  1027.                             intval($command_details['with_promo']['price']);
  1028.                 
  1029.                         $command_details['haveBillingDiscount'] = true;
  1030.                     }
  1031.                     if (isset($command_details['voucher_pricing'])) {
  1032.                 
  1033.                         $command_details['voucher_pricing']['shipping_pricing'] = 0;
  1034.                         $command_details['voucher_pricing']['total_pricing'] =
  1035.                             intval($command_details['voucher_pricing']['command_pricing']);
  1036.                     }
  1037.                 }
  1038.                 if (!$this->restaurantAcceptPrepay($restaurantId)) {
  1039.                     $em->remove($command);
  1040.                     $em->flush();
  1041.                     return new Response($this->serializer->serialize(
  1042.                         $this->errorResponseBlob(null308),
  1043.                         'json'
  1044.                     ));
  1045.                 }
  1046.             
  1047.                  if ($is_preorder == 1) {
  1048.             
  1049.                     if (!$this->restaurantAcceptPreOrder($restaurantId$deliveryRange)) {
  1050.                         $em->remove($command);
  1051.                         $em->flush();
  1052.                         return new Response($this->serializer->serialize(
  1053.                             $this->errorResponseBlob(null307),
  1054.                             'json'
  1055.                         ));
  1056.                     }
  1057.             
  1058.                     $preorderTotalPrice $command_details['is_voucher_used']
  1059.                         ? intval($command_details["voucher_pricing"]["total_pricing"])
  1060.                         : intval($command_details["without_promo"]["pre_order"]["total"]);
  1061.             
  1062.                     if ($isFirstCommandBonusApply['response']) {
  1063.             
  1064.                         if ($command_details['is_voucher_used']) {
  1065.                             $tem_shippingPricing intval($command_details["voucher_pricing"]["shipping_pricing"]);
  1066.                         } else {
  1067.                             $tem_shippingPricing intval($command_details["without_promo"]["pre_order"]["billing"]);
  1068.                         }
  1069.             
  1070.                         $preorderTotalPrice -= $tem_shippingPricing;
  1071.                         $temp_foodPricing $preorderTotalPrice;
  1072.                     }
  1073.             
  1074.             
  1075.                     if ($this->debitClientAction($id$preorderTotalPrice$details1$command->getId())) {
  1076.             
  1077.                         $command->setState(0);
  1078.                         $em->flush();
  1079.             
  1080.                         if ($isFirstCommandBonusApply['response']) {
  1081.                             $this->applyFirstCommandProccess(
  1082.                                 $id,
  1083.                                 $command->getId(),
  1084.                                 $temp_foodPricing,
  1085.                                 $tem_shippingPricing
  1086.                             );
  1087.                         }
  1088.             
  1089.                     } else {
  1090.             
  1091.                         $em->remove($command);
  1092.                         $em->flush();
  1093.             
  1094.                         return new Response($this->serializer->serialize(
  1095.                             $this->errorResponseBlob(null305),
  1096.                             'json'
  1097.                         ));
  1098.                     }
  1099.         
  1100.                 } else {
  1101.             
  1102.                     $orderTotalPrice $command_details['is_voucher_used']
  1103.                         ? intval($command_details["voucher_pricing"]["total_pricing"])
  1104.                         : intval($command_details["with_promo"]["total"]);
  1105.             
  1106.                      if ($isFirstCommandBonusApply['response']) {
  1107.             
  1108.                         if ($command_details['is_voucher_used']) {
  1109.                             $tem_shippingPricing intval($command_details["voucher_pricing"]["shipping_pricing"]);
  1110.                         } else {
  1111.                             $tem_shippingPricing intval($command_details["with_promo"]["billing"]);
  1112.                         }
  1113.             
  1114.                         $orderTotalPrice -= $tem_shippingPricing;
  1115.                         $temp_foodPricing $orderTotalPrice;
  1116.                     }
  1117.             
  1118.                     if ($this->debitClientAction($id$orderTotalPrice$details1$command->getId())) {
  1119.             
  1120.                         $command->setState(0);
  1121.                         $em->flush();
  1122.             
  1123.                         if ($isFirstCommandBonusApply['response']) {
  1124.                             $this->applyFirstCommandProccess(
  1125.                                 $id,
  1126.                                 $command->getId(),
  1127.                                 $temp_foodPricing,
  1128.                                 $tem_shippingPricing
  1129.                             );
  1130.                         }
  1131.             
  1132.                     } else {
  1133.             
  1134.                         // ===== MASTER KEY FALLBACK =====
  1135.                         if (isset($data['master_key']) && $data['master_key'] == $master_key) {
  1136.             
  1137.                             if ($client->getTrustful() == || $this->isEmailAccount($client)) {
  1138.                                 $em->remove($command);
  1139.                                 $em->flush();
  1140.                                 return new Response($this->serializer->serialize(
  1141.                                     $this->errorResponseBlob(null309),
  1142.                                     'json'
  1143.                                 ));
  1144.                             }
  1145.             
  1146.                             $_res $this->debitClientAction(
  1147.                                 $id,
  1148.                                 $orderTotalPrice,
  1149.                                 $details,
  1150.                                 0,
  1151.                                 $command->getId()
  1152.                             );
  1153.             
  1154.                             if ($_res) {
  1155.             
  1156.                                 $command->setState(0);
  1157.                                 $command->setPayAtDelivery(true);
  1158.                                 $em->flush();
  1159.             
  1160.                                 if ($isFirstCommandBonusApply['response']) {
  1161.                                     $this->applyFirstCommandProccess(
  1162.                                         $id,
  1163.                                         $command->getId(),
  1164.                                         $temp_foodPricing,
  1165.                                         $tem_shippingPricing
  1166.                                     );
  1167.                                 }
  1168.             
  1169.                             } else {
  1170.             
  1171.                                 $em->remove($command);
  1172.                                 $em->flush();
  1173.             
  1174.                                 return new Response($this->serializer->serialize(
  1175.                                     $this->errorResponseBlob(null308),
  1176.                                     'json'
  1177.                                 ));
  1178.                             }
  1179.             
  1180.                         } else {
  1181.             
  1182.                             $em->remove($command);
  1183.                             $em->flush();
  1184.             
  1185.                             return new Response($this->serializer->serialize(
  1186.                                 $this->errorResponseBlob(null308),
  1187.                                 'json'
  1188.                             ));
  1189.                         }
  1190.                     }
  1191.                 }
  1192.             }
  1193.             
  1194.     
  1195.             if ($is_preorder == 1) {
  1196.                 $preorder_detail = new PreorderCommandDetails();
  1197.                 $preorder_detail->setCommandId($command->getId());
  1198.                 $preorder_detail->setStart($deliveryRange["start"]);
  1199.                 $preorder_detail->setEnd($deliveryRange["end"]);
  1200.                 $preorder_detail->setDiscount($command_details["discount"]);
  1201.                 $preorder_detail->setPrepayed(1);
  1202.                 $preorder_detail->setCreatedAt(strtotime(date("Y-m-d H:i:s")));
  1203.     
  1204.                 $em->persist($preorder_detail);
  1205.                 $em->flush();
  1206.             }
  1207.     
  1208.             if ($is_voucher == && ($command_details["voucher_pricing"]["valid"] == true || $command_details["is_voucher_used"])) {
  1209.                 $voucher_id intval($data["voucher_id"]);
  1210.                 $voucher $this->entityManager->getRepository(Voucher::class)->find($voucher_id);
  1211.                 $voucher_subs =  $this->entityManager->getRepository(VoucherSubscription::class)->findOneBy([
  1212.                     'userId' => $id,
  1213.                     'voucherId' => $voucher_id,
  1214.                 ]);
  1215.                 if ($voucher_subs != null) {
  1216.                     $usage_count count($this->entityManager->getRepository(VoucherUsage::class)->findBy([
  1217.                         'userId' => $id,
  1218.                         'voucherId' => $voucher_id,
  1219.                         'isReallyUsed' => 1
  1220.                     ]));
  1221.     
  1222.                     if ($voucher != null) {
  1223.                         if (($usage_count 1) >= intval($voucher->getUseCount())) {
  1224.                             $voucher_subs->setState(1);
  1225.                         }
  1226.                         $voucher_subs->setUseCount($usage_count 1);
  1227.                         $new_usage = new VoucherUsage();
  1228.                         $new_usage->setUserId($id);
  1229.                         $new_usage->setVoucherId($voucher_id);
  1230.                         $new_usage->setCommandId($command->getId());
  1231.                         $new_usage->setIsReallyUsed(1);
  1232.                         $new_usage->setCreatedAt(strtotime(date('Y-m-d H:i:s')));
  1233.                         $em->persist($new_usage);
  1234.                         $reward 0;
  1235.                         $check_voucher_owners $this->entityManager->getRepository(VoucherOwner::class)->findBy([
  1236.                             'voucherId' => $voucher_id
  1237.                         ]);
  1238.     
  1239.                         if ($check_voucher_owners != null) {
  1240.                             if ($command_details["voucher_pricing"]["owner"]["is_rewarded"] == 1) {
  1241.                                 if ($command_details["voucher_pricing"]["owner"]["reward_on_food"] == 0) {
  1242.                                     $reward $command_details["voucher_pricing"]["owner"]["reward_cash_value"];
  1243.                                 } else {
  1244.                                     $reward $command_details["voucher_pricing"]["owner"]["reward_on_food"] + $command_details["voucher_pricing"]["owner"]["reward_on_billing"];
  1245.                                 }
  1246.                             }
  1247.                             if ($reward 0) {
  1248.     
  1249.                                 foreach ($check_voucher_owners as $owner) {
  1250.                                     $voucher_transaction = new VoucherTransaction();
  1251.                                     $voucher_transaction->setUserId($owner->getUserId());
  1252.                                     $voucher_transaction->setVoucherId($voucher_id);
  1253.                                     $voucher_transaction->setValue($reward);
  1254.                                     $voucher_transaction->setType(1);
  1255.                                     $voucher_transaction->setCommandId($command->getId());
  1256.                                     $voucher_transaction->setState(0);
  1257.                                     $voucher_transaction->setCreatedAt(strtotime(date('Y-m-d H:i:s')));
  1258.                                     $voucher_transaction->setUpdatedAt(strtotime(date('Y-m-d H:i:s')));
  1259.                                     $em->persist($voucher_transaction);
  1260.                                 }
  1261.                             }
  1262.                         }
  1263.                     }
  1264.                 }
  1265.                 $em->flush();
  1266.             }
  1267.     
  1268.         }catch(Throwable $e){
  1269.             error_log($e->getMessage());
  1270.             error_log($e->getTraceAsString());
  1271.         }
  1272.         $pusher $this->getPusher();
  1273.         $message = [];
  1274.         $message['id'] = $command->getId();
  1275.         $message['state'] = $command->getState();
  1276.         $pusher->trigger($this->getParameter('PUSHER_APP_CHANNEL'), BaseController::NEW_COMMAND$message);
  1277.         if(!$is_preorder){
  1278.             try{
  1279.                 $deno_api 'https://useful-tuna-68.deno.dev/';
  1280.             if(isset($saved_data['user_abonnement']) && $saved_data['user_abonnement']!=null){
  1281.             $this->http_client->request('POST'$deno_api, [
  1282.                 'json' => [
  1283.                     'user_id' => (string) $user->getId(),
  1284.                     'subscription_id' => (string) $saved_data['user_abonnement']['pack']['id'],
  1285.                     'codeAbo' => (string) $saved_data['user_abonnement']['codeAbonnement'],
  1286.                     'command_id' => (string) $command->getId(),
  1287.                     'total_price' => (string) $command_details["with_promo"]["total"],
  1288.                     'prix_livraison'=>(string) $command->getShippingPricing()
  1289.                 ],
  1290.             ]);
  1291.             }
  1292.             }catch(Throwable $e){
  1293.                 error_log("API proxy failed: ".$e->getMessage());
  1294.             }
  1295.         }
  1296.         $jsonData json_encode([
  1297.             "food_command" => $command->getFoodCommand(),
  1298.             "restaurant_id" => $restaurant->getId(),
  1299.             "shipping_address" => $adress['id'],
  1300.             "voucher_id" => $voucher_id,
  1301.             "use_kaba_point" => $use_kaba_point,
  1302.         ]);
  1303.         $Billingrequest = new Request(
  1304.             [],
  1305.             [],
  1306.             [],
  1307.             [],
  1308.             [],
  1309.             ['CONTENT_TYPE' => 'application/json'],
  1310.             $jsonData
  1311.         );
  1312.         $getBilling $this->getCommandBillingWithVoucherAction($Billingrequest);
  1313.         $getBillingContent $getBilling->getContent();
  1314.         $getBillingData json_decode($getBillingContenttrue);
  1315.         $this->createPaymentBill($getBillingData['data'], $command->getId());
  1316.         $client_balance $this->getBalance($id);
  1317.         $data = [];
  1318.         $data["balance"] = $client_balance;
  1319.         $data["pre_order"] = $is_preorder;
  1320.         $data["pre_order_hour"] = $deliveryRange;
  1321.         $data["voucher_data"] = $command_details["voucher_pricing"];
  1322.         $response["error"] = 0;
  1323.         $response["code"] = 200;
  1324.         $response["message"] = "200 OK";
  1325.         $response["data"] = $data;
  1326.         $pusher->trigger($this->getParameter('PUSHER_APP_CHANNEL'), BaseController::UPDATE_COMMAND_STATE$message);
  1327.      
  1328.         $sql 'SELECT * FROM devices WHERE id = :id';
  1329.         $device $this->connection->fetchAssociative($sql, ['id' => $user->getDeviceId()]);  
  1330.         $push_token $device['push_token'];
  1331.         //call automation
  1332.         /*
  1333.         try {
  1334.             $url = 'https://stats.kaba-delivery.com/automation/order/assign/to/livreur';
  1335.             $response = $this->http_client->request('POST', $url, [
  1336.                 'json' => [
  1337.                     'command_id' => $command->getId()
  1338.                 ],
  1339.             ]);
  1340.         }catch(Throwable $e){
  1341.             
  1342.         }
  1343.         */
  1344.         return new Response($this->serializer->serialize($this->okResponseBlob(['command_id'=>$command->getId(),'total_price'=>$command_details["with_promo"]["total"],"details"=>$command_details]), 'json'));
  1345.     }
  1346.     /**
  1347.      * @Route("mobile/api/command/billing/v4/get", name="user_mobile_v4_get_command_billing:", methods={"POST"})
  1348.      */
  1349.     public function getCommandBillingWithVoucherAction(Request $request)
  1350.     {
  1351.         $currentToken $this->get('security.token_storage')->getToken();
  1352.         $user $currentToken->getUser();
  1353.         $id $user->getId();
  1354.         $data json_decode($request->getContent(), true);
  1355.         if (
  1356.             isset($data["restaurant_id"]) &&
  1357.             isset($data["shipping_address"]) &&
  1358.             $data["restaurant_id"] != null &&
  1359.             $data["shipping_address"] != null &&
  1360.             count($data["food_command"]) != 0
  1361.         ) {
  1362.             //check user's number of order so far 
  1363.             $nb_order $this->checkNumberOfOrderFoUser($id); 
  1364.             if($nb_order >= && $nb_order <= 5){
  1365.                 $data['voucher_id']=null;
  1366.                 $data['use_kaba_point']=false;
  1367.             }
  1368.             $restaurant $this->entityManager->getRepository(RestaurantConfig::class)->find(intval($data["restaurant_id"]));
  1369.             $address =  $this->entityManager->getRepository(Adresses::class)->find(intval($data["shipping_address"]));
  1370.             $configs_with_voucher $this->configsWithVoucher($data$currentToken$user$restaurant$address);
  1371.             $res = [];
  1372.             $res["promotion_pricing"] = $this->getPromotionPricing($data$configs_with_voucher);
  1373.             $res["command_pricing"] = $this->calculate_command_pricing($data["food_command"]);
  1374.             $res["account_balance"] = $this->getBalance($id);
  1375.             $res["distance"] = $this->getDistance($restaurant->getLocation(), $address->getLocation());
  1376.             $res["shipping_pricing"] = $this->calculate_shipping_price($res["distance"], $currentToken);
  1377.             $res["kaba_point"] = $this->get_kaba_point($id$res['shipping_pricing']);
  1378.             $res['is_new_user']=false;
  1379.             $res["promotion_shipping_pricing"] = $this->getPromotionOnShipping($restaurant$data$address$currentToken$user$configs_with_voucher$res['shipping_pricing'], $res['kaba_point']);
  1380.             try{
  1381.                 if($nb_order >= && $nb_order <= 5){
  1382.                     $promotion $this->entityManager->getRepository(NewUserPromotion::class)->findAll();
  1383.                     if($promotion){
  1384.                         if($promotion[0]->getIsActive()==true){
  1385.                             $promotion_for_new_user $promotion[0] ->getValue();
  1386.                             $res["promotion_shipping_pricing"] = $res['shipping_pricing']-$promotion_for_new_user;
  1387.                             $res['is_new_user']=true;
  1388.                         }else{
  1389.                            
  1390.                         }
  1391.                     }
  1392.                 }
  1393.             }catch(Throwable $e){
  1394.                 
  1395.             }
  1396.             $res['additional_fees'] = $this->getAdditionalFeesPrice($data['food_command'], $res['command_pricing'], $res['shipping_pricing'], $address$restaurant);
  1397.             $res['additional_fees_total_price'] = $this->getAdditionalFeesTotalPricing($res["additional_fees"]);
  1398.             $res["total_pricing"] = $this->get_total_pricing($res$configs_with_voucher$data$id$res["kaba_point"]);
  1399.             $res['total_normal_pricing'] = intval($res["command_pricing"]) + intval($res["shipping_pricing"]) + intval($res['additional_fees_total_price']);
  1400.             $res["remise"] = $this->get_remise($id$res$data$res["kaba_point"]);
  1401.             $res["out_of_range"] = $this->isOutOfRange($res["distance"]);
  1402.             $res["pay_at_delivery"] = $restaurant->getPayAtDelivery();
  1403.             $res["prepayed"] = $restaurant->getPrepayed();
  1404.             $res["trustful"] = $user->getTrustful();
  1405.             $res["max_pay"] = intval($restaurant->getMaxPay());
  1406.             $res["cooking_time"] = (int)$restaurant->getCookingTime();
  1407.             $res['eligible_vouchers'] = $this->getUserEligibleVoucher($id);
  1408.             
  1409.             $additional_fee $this->entityManager->getRepository(AdditionalFees::class)->findOneBy(["fee_type" => AdditionnalFeeType::COMMISSION_FEE]);
  1410.             
  1411.             try{
  1412.                 $commission_additional_fee $this->entityManager->getRepository(RestoFraisSupp::class)->findOneBy(["resto_id" => $data['restaurant_id'], "additional_fee_id" => $additional_fee->getId()]);
  1413.                 $isEnabled =  $commission_additional_fee->isFeeEnabled();
  1414.                 
  1415.             }catch(Throwable $e){
  1416.                 $isEnabled false;
  1417.             }
  1418.             if ($isEnabled == true) {
  1419.                 $sql 'SELECT * FROM devices WHERE id = :id';
  1420.                 $device $this->connection->fetchAssociative($sql, ['id' => $user->getDeviceId()]);  
  1421.                 $push_token $device['push_token'];
  1422.                 try{
  1423.                     $notif = [];
  1424.                     $notif["error"] = 0;
  1425.                     $notif["message"] = "nothing";
  1426.                     $notif["data"] = [];
  1427.                     $notif["data"]["notification"] = [];
  1428.                     $notif["data"]["notification"]["title"] = "ℹ️ Frais supplémentaires";
  1429.                     $notif["data"]["notification"]["body"] = "Des frais supplémentaires sont appliqués chez ce marchand";
  1430.                     $notif["data"]["notification"]["image_link"] = '';
  1431.                     $notif["data"]["notification"]["destination"] = [];
  1432.                     $notif["data"]["notification"]["destination"]["type"] = 200;
  1433.                     $notif["data"]["notification"]["destination"]["priority"] = 2;
  1434.                     $notif["data"]["notification"]["destination"]["amount"] = intval(0);
  1435.                     $notif["data"]["notification"]["destination"]["is_out_of_app"] = intval(0);
  1436.                     $notif["data"]["notification"]["destination"]["product_id"] = intval(0);
  1437.                   //  $this->sendNotificationToDeviceV2([$push_token],"Des frais supplémentaires sont appliqués chez ce marchand",$notif,1);
  1438.                 }catch(Throwable $e){
  1439.                 }
  1440.             }
  1441.             return new Response($this->serializer->serialize($this->okResponseBlob($res), 'json'));
  1442.         } else {
  1443.             return new Response($this->serializer->serialize($this->errorResponseBlob('Invalid parameter'), 'json'));
  1444.         }
  1445.     }
  1446.     /**
  1447.      * @Route("mobile/api/command/v4/create", name="mobile_api_command_v4_create", methods={"POST"})
  1448.      */
  1449.     public function createCommandWithVoucherV4Action(Request $request)
  1450.     {
  1451.         $currentToken $this->get('security.token_storage')->getToken();
  1452.         $user $currentToken->getUser();
  1453.         $id $user->getId();
  1454.         $data json_decode($request->getContent(), true);
  1455.         $is_preorder 0;
  1456.         $is_voucher 0;
  1457.              //check user's number of order so far 
  1458.        $nb_order $this->checkNumberOfOrderFoUser($id); 
  1459.         if($nb_order >= && $nb_order <= 5){
  1460.             $data['voucher_id']=null;
  1461.             $data['use_kaba_point']=false;
  1462.         }
  1463.         $deliveryRange = [];
  1464.         if (isset($data["pre_order"]) && $data["pre_order"] == && isset($data["pre_order_hour"]) && $data["pre_order_hour"] != null) {
  1465.             $deliveryRange = array('start' => $data["pre_order_hour"]["start"], 'end' => $data["pre_order_hour"]["end"]);
  1466.             $is_preorder 1;
  1467.         }
  1468.         $restaurantId $this->getRestaurantId($data["food_command"]);
  1469.         $adress $this->getAdress($data["shipping_address"]);
  1470.         if ($restaurantId == -1)
  1471.             return new Response($this->serializer->serialize($this->errorResponseBlob(null301), 'json'));
  1472.         if ($adress == -1)
  1473.             return new Response($this->serializer->serialize($this->errorResponseBlob(null304), 'json'));
  1474.         $voucher_id null;
  1475.         if (isset($data["voucher_id"]) && $data["voucher_id"] != null) {
  1476.             $voucher_id intval($data["voucher_id"]);
  1477.             $is_voucher 1;
  1478.         }
  1479.         $use_kaba_point false;
  1480.         if (isset($data["use_kaba_point"]) && $data["use_kaba_point"] != null)
  1481.             $use_kaba_point $data["use_kaba_point"];
  1482.         $command_details $this->getCommandDetails2($data["food_command"], $restaurantId$adress$is_preorder$voucher_id$id$use_kaba_point);
  1483.         $data["food_command"] = $command_details["foods"];
  1484.         $restaurant =  $this->entityManager->getRepository(RestaurantConfig::class)->find($restaurantId);
  1485.         $details "Achat de " " " $command_details["food_litteral"] . " " "à" " " $restaurant->getName();
  1486.         if (!($this->checkValidUser($id)))
  1487.             return new Response($this->serializer->serialize($this->errorResponseBlob(null306), 'json'));
  1488.         $master_key md5('kabapeur');
  1489.         if (!(isset($data['master_key']) && $data['master_key'] == $master_key)) {
  1490.             if (!($this->checkTransactionPassword($id$data["transaction_password"])))
  1491.                 return new Response($this->serializer->serialize($this->errorResponseBlob(null300), 'json'));
  1492.         }
  1493.         $isFirstCommandBonusApply $this->isFirstCommandBonusApply($id);
  1494.         if ($isFirstCommandBonusApply['response'] && $isFirstCommandBonusApply['type'] == '1') {
  1495.             $haveBillingDiscount true;
  1496.         } else {
  1497.             $haveBillingDiscount $command_details["haveBillingDiscount"];
  1498.         }
  1499.         $client =  $this->entityManager->getRepository(Client::class)->find($id);
  1500.         $command = new Command();
  1501.         $em $this->entityManager;
  1502.         $word false;
  1503.         while ($word == false) {
  1504.             $word $this->generateWord();
  1505.         }
  1506.         $command->setPassPhrase($word);
  1507.         if ($command_details["is_kaba_point_used"]) {
  1508.             $kabaPointTransaction $this->debitKabaPointAccount($idintval($command_details["kaba_point_used_amount"]));
  1509.             if ($kabaPointTransaction['state']) {
  1510.                 $command->setKabaPoint(intval($kabaPointTransaction["transaction"]["id"]));
  1511.                 $command->setKabaPointAmount(intval($command_details["kaba_point_used_amount"]));
  1512.             } else {
  1513.                 $command_details["food_billing"] += intval($command_details["kaba_point_used_amount"]);
  1514.                 $command_details["email_shipping_pricing"] += intval($command_details["kaba_point_used_amount"]);
  1515.                 $command_details["phoneNumber_shipping_pricing"] += intval($command_details["kaba_point_used_amount"]);
  1516.             }
  1517.         }
  1518.         $realyShippingPrice $isFirstCommandBonusApply['response'] && $isFirstCommandBonusApply['type'] == '1' $command_details["food_billing"];
  1519.         $command->setFoodCommand($data["food_command"]);
  1520.         $command->setPreOrder($is_preorder);
  1521.         $command->setPayAtDelivery($data["pay_at_delivery"]);
  1522.         $command->setClientId($id);
  1523.         $command->setClient($user);
  1524.         $command->setState(-1);
  1525.         $command->setRestaurantId($restaurantId);
  1526.         $command->setRestaurant($restaurant);
  1527.         $command->setShippingAddress($adress);
  1528.         $command->setHaveBillingDiscount($haveBillingDiscount);
  1529.         $command->setExtraShippingPricing($command_details["extra_shipping_pricing"] > $realyShippingPrice $command_details["extra_shipping_pricing"]);
  1530.         $command->setBaseShippingPricing($command_details["base_shipping_pricing"]);
  1531.         $command->setEmailAccountShippingPricing($command_details["email_shipping_pricing"]);
  1532.         $command->setPhoneNumberAccountShippingPricing($command_details["phoneNumber_shipping_pricing"]);
  1533.         $command->setShippingPricing($realyShippingPrice);
  1534.         try{
  1535.             if($nb_order >= && $nb_order <= 5){
  1536.                 $promotion $this->entityManager->getRepository(NewUserPromotion::class)->findAll();
  1537.                 if($promotion){
  1538.                     if($promotion[0] ->getIsActive()==true){
  1539.                         $promotion_for_new_user $promotion[0] ->getValue();
  1540.                         $command->setHaveBillingDiscount(true);
  1541.                         $command->setShippingPricing($realyShippingPrice-$promotion_for_new_user);
  1542.                      }
  1543.                 }
  1544.             }
  1545.         }catch(Throwable $e){
  1546.             
  1547.         }
  1548.         $command->setStartTime(date('Y-m-d H:i:s'));
  1549.         $command->setStartDate(date('Y-m-d'));
  1550.         $command->setLastUpdate(date('Y-m-d H:i:s'));
  1551.         $client_commands $this->entityManager->getRepository(Command::class)->findBy([
  1552.             'clientId' => $id,
  1553.         ]);
  1554.         if (count($client_commands) > 0)
  1555.             $command->setIsFirstOrder(false);
  1556.         else
  1557.             $command->setIsFirstOrder(true);
  1558.         if ($command_details['is_voucher_used'])
  1559.             $command->setHasVoucher(true);
  1560.         else
  1561.             $command->setHasVoucher(false);
  1562.         if (isset($data["infos"]) && $data["infos"] != null)
  1563.             $command->setInfos($data["infos"]);
  1564.                 $now = new \DateTime();
  1565.                 $twoMinutesAgo = (clone $now)->modify('-1 minute');
  1566.                 $existingCommand $this->entityManager->getRepository(Command::class)->createQueryBuilder('c')
  1567.                     ->where('c.clientId = :clientId')
  1568.                     ->andWhere('c.restaurantId = :restaurantId')
  1569.                     ->andWhere('c.foodCommand = :foodCommand')
  1570.                     ->andWhere('c.startTime BETWEEN :start AND :now')
  1571.                     ->setParameter('clientId'$id)
  1572.                     ->setParameter('restaurantId'$restaurantId)
  1573.                     ->setParameter('foodCommand'$data['food_command'])
  1574.                     ->setParameter('start'$twoMinutesAgo->format('Y-m-d H:i:s'))
  1575.                     ->setParameter('now'$now->format('Y-m-d H:i:s'))
  1576.                     ->getQuery()
  1577.                     ->getOneOrNullResult();
  1578.                     if ($existingCommand) { 
  1579.                         $jsonData json_encode([
  1580.                                     "food_command" => $command->getFoodCommand(),
  1581.                                     "restaurant_id" => $restaurant->getId(),
  1582.                                     "shipping_address" => $adress['id'],
  1583.                                     "voucher_id" => $voucher_id,
  1584.                                     "use_kaba_point" => $use_kaba_point,
  1585.                                 ]);
  1586.                                 $Billingrequest = new Request(
  1587.                                     [],
  1588.                                     [],
  1589.                                     [],
  1590.                                     [],
  1591.                                     [],
  1592.                                     ['CONTENT_TYPE' => 'application/json'],
  1593.                                     $jsonData
  1594.                                 );
  1595.                                 $getBilling $this->getCommandBillingWithVoucherAction($Billingrequest);
  1596.                                 $getBillingContent $getBilling->getContent();
  1597.                                 $getBillingData json_decode($getBillingContenttrue);
  1598.                                 $this->createPaymentBill($getBillingData['data'], $command->getId());
  1599.                                 return new JsonResponse($getBillingData200);
  1600.                         }
  1601.             
  1602.                     $em->persist($command);
  1603.                     $em->flush();        
  1604.         
  1605.             if ($data["device"]["push_token"] != null) {
  1606.             $device =  $this->entityManager->getRepository(Devices::class)->findOneBy([
  1607.                 'pushToken' => $data["device"]["push_token"]
  1608.             ]);
  1609.             if ($device != null) {
  1610.                 $client->setDeviceId($device->getId());
  1611.             } else {
  1612.                 $device_id $this->createDevice($data["device"], 1);
  1613.                 $client->setDeviceId($device_id);
  1614.             }
  1615.         }
  1616.         $temp_foodPricing 0;
  1617.         $tem_shippingPricing 0;
  1618.         if ($data["pay_at_delivery"] == true) {
  1619.             if ($this->restaurantAcceptPayAtArrival($restaurantId)) {
  1620.                 if ($command_details['is_voucher_used']) {
  1621.                     $pay_at_delivery_total_price intval($command_details["voucher_pricing"]["total_pricing"]);
  1622.                     if ($isFirstCommandBonusApply['response']) {
  1623.                         $pay_at_delivery_total_price -= intval($command_details["voucher_pricing"]["shipping_pricing"]);
  1624.                         $temp_foodPricing $pay_at_delivery_total_price;
  1625.                         $tem_shippingPricing intval($command_details["voucher_pricing"]["shipping_pricing"]);
  1626.                     }
  1627.                 } else {
  1628.                     $pay_at_delivery_total_price intval($command_details["with_promo"]["total"]);
  1629.                     if ($isFirstCommandBonusApply['response']) {
  1630.                         $pay_at_delivery_total_price -= intval($command_details["with_promo"]["billing"]);
  1631.                         $temp_foodPricing $pay_at_delivery_total_price;
  1632.                         $tem_shippingPricing intval($command_details["with_promo"]["billing"]);
  1633.                     }
  1634.                 }
  1635.                 $res $this->debitClientAction($id$pay_at_delivery_total_price$details0$command->getId());
  1636.                 if ($res) {
  1637.                     $command->setState(0);
  1638.                     $em->flush();
  1639.                     $isFirstCommandBonusApply['response'] ? $this->applyFirstCommandProccess($id$command->getId(), $temp_foodPricing$tem_shippingPricing) : '';
  1640.                 } else {
  1641.                     $em->remove($command);
  1642.                     $em->flush();
  1643.                 }
  1644.             } else {
  1645.                 $em->remove($command);
  1646.                 $em->flush();
  1647.                 return new Response($this->serializer->serialize($this->errorResponseBlob(null305), 'json'));
  1648.             }
  1649.         } else if ($data["pay_at_delivery"] == false) { // prepay
  1650.             if ($this->restaurantAcceptPrepay($restaurantId)) {
  1651.                 if ($is_preorder == 1) {
  1652.                     if ($this->restaurantAcceptPreOrder($restaurantId$deliveryRange)) {
  1653.                         if ($command_details['is_voucher_used']) {
  1654.                             $preorderTotalPrice intval($command_details["voucher_pricing"]["total_pricing"]);
  1655.                             if ($isFirstCommandBonusApply['response']) {
  1656.                                 $preorderTotalPrice -= intval($command_details["voucher_pricing"]["shipping_pricing"]);
  1657.                                 $temp_foodPricing $preorderTotalPrice;
  1658.                                 $tem_shippingPricing intval($command_details["voucher_pricing"]["shipping_pricing"]);
  1659.                             }
  1660.                         } else {
  1661.                             $preorderTotalPrice intval($command_details["without_promo"]["pre_order"]["total"]);
  1662.                             if ($isFirstCommandBonusApply['response']) {
  1663.                                 $preorderTotalPrice -= intval($command_details["without_promo"]["pre_order"]["billing"]);
  1664.                                 $temp_foodPricing $preorderTotalPrice;
  1665.                                 $tem_shippingPricing intval($command_details["without_promo"]["pre_order"]["billing"]);
  1666.                             }
  1667.                         }
  1668.                         if ($this->debitClientAction($id$preorderTotalPrice$details1$command->getId())) {
  1669.                             $command->setState(0);
  1670.                             $em->flush();
  1671.                             $isFirstCommandBonusApply['response'] ? $this->applyFirstCommandProccess($id$command->getId(), $temp_foodPricing$tem_shippingPricing) : '';
  1672.                         } else {
  1673.                             $em->remove($command);
  1674.                             $em->flush();
  1675.                             return new Response($this->serializer->serialize($this->errorResponseBlob(null305), 'json'));
  1676.                         }
  1677.                     } else {
  1678.                         $em->remove($command);
  1679.                         $em->flush();
  1680.                         return new Response($this->serializer->serialize($this->errorResponseBlob(null307), 'json'));
  1681.                     }
  1682.                 } else {
  1683.                     if ($command_details['is_voucher_used']) {
  1684.                         $orderTotalPrice intval($command_details["voucher_pricing"]["total_pricing"]);
  1685.                         if ($isFirstCommandBonusApply['response']) {
  1686.                             $orderTotalPrice -= intval($command_details["voucher_pricing"]["shipping_pricing"]);
  1687.                             $temp_foodPricing $orderTotalPrice;
  1688.                             $tem_shippingPricing intval($command_details["voucher_pricing"]["shipping_pricing"]);
  1689.                         }
  1690.                     } else {
  1691.                         $orderTotalPrice intval($command_details["with_promo"]["total"]);
  1692.                         if ($isFirstCommandBonusApply['response']) {
  1693.                             $orderTotalPrice -= intval($command_details["with_promo"]["billing"]);
  1694.                             $temp_foodPricing $orderTotalPrice;
  1695.                             $tem_shippingPricing intval($command_details["with_promo"]["billing"]);
  1696.                         }
  1697.                     }
  1698.                     if ($this->debitClientAction($id$orderTotalPrice$details1$command->getId())) {
  1699.                         $command->setState(0);
  1700.                         $em->flush();
  1701.                         $isFirstCommandBonusApply['response'] ? $this->applyFirstCommandProccess($id$command->getId(), $temp_foodPricing$tem_shippingPricing) : '';
  1702.                     } else {
  1703.                         if ((isset($data['master_key']) && $data['master_key'] == $master_key)) {
  1704.                             if ($client->getTrustful() == || $this->isEmailAccount($client)) {
  1705.                                 $em->remove($command);
  1706.                                 $em->flush();
  1707.                                 return new Response($this->serializer->serialize($this->errorResponseBlob(null309), 'json'));
  1708.                             }
  1709.                             $_res $this->debitClientAction($id$orderTotalPrice$details0$command->getId());
  1710.                             if ($_res) {
  1711.                                 $command->setState(0);
  1712.                                 $command->setPayAtDelivery(true);
  1713.                                 $trans $this->entityManager->getRepository(Transaction::class)->findOneBy([
  1714.                                     "commandId" => $command->getId()
  1715.                                 ]);
  1716.                                 $em->flush();
  1717.                                 $isFirstCommandBonusApply['response'] ? $this->applyFirstCommandProccess($id$command->getId(), $temp_foodPricing$tem_shippingPricing) : '';
  1718.                             } else {
  1719.                                 $em->remove($command);
  1720.                                 $em->flush();
  1721.                                 return new Response($this->serializer->serialize($this->errorResponseBlob(null308), 'json'));
  1722.                             }
  1723.                         } else {
  1724.                             $em->remove($command);
  1725.                             $em->flush();
  1726.                             return new Response($this->serializer->serialize($this->errorResponseBlob(null308), 'json'));
  1727.                         }
  1728.                     }
  1729.                 }
  1730.             } else {
  1731.                 $em->remove($command);
  1732.                 $em->flush();
  1733.                 return new Response($this->serializer->serialize($this->errorResponseBlob(null308), 'json'));
  1734.             }
  1735.         }
  1736.         if ($is_preorder == 1) {
  1737.             $preorder_detail = new PreorderCommandDetails();
  1738.             $preorder_detail->setCommandId($command->getId());
  1739.             $preorder_detail->setStart($deliveryRange["start"]);
  1740.             $preorder_detail->setEnd($deliveryRange["end"]);
  1741.             $preorder_detail->setDiscount($command_details["discount"]);
  1742.             $preorder_detail->setPrepayed(1);
  1743.             $preorder_detail->setCreatedAt(strtotime(date("Y-m-d H:i:s")));
  1744.             $em->persist($preorder_detail);
  1745.             $em->flush();
  1746.         }
  1747.         if ($is_voucher == && ($command_details["voucher_pricing"]["valid"] == true || $command_details["is_voucher_used"])) {
  1748.             $voucher_id intval($data["voucher_id"]);
  1749.             $voucher $this->entityManager->getRepository(Voucher::class)->find($voucher_id);
  1750.             $voucher_subs =  $this->entityManager->getRepository(VoucherSubscription::class)->findOneBy([
  1751.                 'userId' => $id,
  1752.                 'voucherId' => $voucher_id,
  1753.             ]);
  1754.             if ($voucher_subs != null) {
  1755.                 $usage_count count($this->entityManager->getRepository(VoucherUsage::class)->findBy([
  1756.                     'userId' => $id,
  1757.                     'voucherId' => $voucher_id,
  1758.                     'isReallyUsed' => 1
  1759.                 ]));
  1760.                 if ($voucher != null) {
  1761.                     if (($usage_count 1) >= intval($voucher->getUseCount())) {
  1762.                         $voucher_subs->setState(1);
  1763.                     }
  1764.                     $voucher_subs->setUseCount($usage_count 1);
  1765.                     $new_usage = new VoucherUsage();
  1766.                     $new_usage->setUserId($id);
  1767.                     $new_usage->setVoucherId($voucher_id);
  1768.                     $new_usage->setCommandId($command->getId());
  1769.                     $new_usage->setIsReallyUsed(1);
  1770.                     $new_usage->setCreatedAt(strtotime(date('Y-m-d H:i:s')));
  1771.                     $em->persist($new_usage);
  1772.                     $reward 0;
  1773.                     $check_voucher_owners $this->entityManager->getRepository(VoucherOwner::class)->findBy([
  1774.                         'voucherId' => $voucher_id
  1775.                     ]);
  1776.                     if ($check_voucher_owners != null) {
  1777.                         if ($command_details["voucher_pricing"]["owner"]["is_rewarded"] == 1) {
  1778.                             if ($command_details["voucher_pricing"]["owner"]["reward_on_food"] == 0) {
  1779.                                 $reward $command_details["voucher_pricing"]["owner"]["reward_cash_value"];
  1780.                             } else {
  1781.                                 $reward $command_details["voucher_pricing"]["owner"]["reward_on_food"] + $command_details["voucher_pricing"]["owner"]["reward_on_billing"];
  1782.                             }
  1783.                         }
  1784.                         if ($reward 0) {
  1785.                             foreach ($check_voucher_owners as $owner) {
  1786.                                 $voucher_transaction = new VoucherTransaction();
  1787.                                 $voucher_transaction->setUserId($owner->getUserId());
  1788.                                 $voucher_transaction->setVoucherId($voucher_id);
  1789.                                 $voucher_transaction->setValue($reward);
  1790.                                 $voucher_transaction->setType(1);
  1791.                                 $voucher_transaction->setCommandId($command->getId());
  1792.                                 $voucher_transaction->setState(0);
  1793.                                 $voucher_transaction->setCreatedAt(strtotime(date('Y-m-d H:i:s')));
  1794.                                 $voucher_transaction->setUpdatedAt(strtotime(date('Y-m-d H:i:s')));
  1795.                                 $em->persist($voucher_transaction);
  1796.                             }
  1797.                         }
  1798.                     }
  1799.                 }
  1800.             }
  1801.             $em->flush();
  1802.         }
  1803.         if ($restaurant->getDeviceId() != null) {
  1804.             $device $this->entityManager->getRepository(Devices::class)->find($restaurant->getDeviceId());
  1805.             if ($device != null && $device->getPushToken() != '') {
  1806.                 $devices_array = [];
  1807.                 array_push($devices_array$device->getPushToken());
  1808.                 $devices_resto =[];
  1809.                 $devices_resto = [];
  1810.                 $device_resto $this->entityManager->getRepository(Devices::class)->find($restaurant->getDeviceId());
  1811.                if ($device_resto != null && $device_resto->getPushToken() != null
  1812.                      array_push($devices_resto$device_resto->getPushToken());
  1813.              
  1814.                 $notif = [];
  1815.                 $notif["error"] = 0;
  1816.                 $notif["message"] = "nothing";
  1817.                 $notif["data"] = [];
  1818.                 $notif["data"]["notification"] = [];
  1819.                 $notif["data"]["notification"]["title"] = "Kaba";
  1820.                 $notif["data"]["notification"]["body"] = "Vous avez une nouvelle commande !";
  1821.                 $notif["data"]["notification"]["image_link"] = '';
  1822.                 $notif["data"]["notification"]["destination"] = [];
  1823.                 $notif["data"]["notification"]["destination"]["type"] = 154;
  1824.                 $notif["data"]["notification"]["destination"]["priority"] = 300;
  1825.                 $notif["data"]["notification"]["destination"]["product_id"] = intval($command->getId());
  1826.                 $notif["data"]["notification"]["destination"]["is_out_of_app"] = intval(0);
  1827.             
  1828.                 try {
  1829.                     $this->sendNotificationToDeviceV2($devices_resto"Vous avez une nouvelle commande !"$notif2);
  1830.                 } catch (\Throwable $e) {
  1831.                 }
  1832.                 
  1833.             }
  1834.         }
  1835.         $jsonData json_encode([
  1836.             "food_command" => $command->getFoodCommand(),
  1837.             "restaurant_id" => $restaurant->getId(),
  1838.             "shipping_address" => $adress['id'],
  1839.             "voucher_id" => $voucher_id,
  1840.             "use_kaba_point" => $use_kaba_point,
  1841.         ]);
  1842.         $Billingrequest = new Request(
  1843.             [],
  1844.             [],
  1845.             [],
  1846.             [],
  1847.             [],
  1848.             ['CONTENT_TYPE' => 'application/json'],
  1849.             $jsonData
  1850.         );
  1851.         $getBilling $this->getCommandBillingWithVoucherAction($Billingrequest);
  1852.         $getBillingContent $getBilling->getContent();
  1853.         $getBillingData json_decode($getBillingContenttrue);
  1854.         $this->createPaymentBill($getBillingData['data'], $command->getId());
  1855.         $client_balance $this->getBalance($id);
  1856.         $data = [];
  1857.         $data["balance"] = $client_balance;
  1858.         $data["pre_order"] = $is_preorder;
  1859.         $data["pre_order_hour"] = $deliveryRange;
  1860.         $data["voucher_data"] = $command_details["voucher_pricing"];
  1861.         $response["error"] = 0;
  1862.         $response["code"] = 200;
  1863.         $response["message"] = "200 OK";
  1864.         $response["data"] = $data;
  1865.         $pusher $this->getPusher();
  1866.         $message = [];
  1867.         $message['id'] = $command->getId();
  1868.         $message['state'] = $command->getState();
  1869.         $pusher->trigger($this->getParameter('PUSHER_APP_CHANNEL'), BaseController::NEW_COMMAND$message);
  1870.         return new JsonResponse($getBillingData200);
  1871.     }
  1872.     /**
  1873.      * @Route("mobile/api/command/details/v4/get", name="user_mobile_v4_get_command_details", methods={"POST"})
  1874.      */
  1875.     public function getCommandDetailsWithVoucherAction(Request $request)
  1876.     {
  1877.         $currentToken $this->get('security.token_storage')->getToken();
  1878.         $id $currentToken->getUser()->getId();
  1879.         $json_data $request->getContent();
  1880.         $data json_decode($json_datatrue);
  1881.         $command_id $data["command_id"];
  1882.         $command =  $this->entityManager->getRepository(Command::class)->find(intval($command_id));
  1883.         if ($command == null) {
  1884.             return new Response($this->serializer->serialize($this->errorResponseBlob([]), 'json'), 200);
  1885.         }
  1886.         // command has been found,
  1887.         $vouch $this->madeUpCommandItemWithVoucher($command);
  1888.         if ($vouch["voucher_entity"] != []) {
  1889.             $vouch["voucher_entity"]["already_used_count"] = count($this->entityManager->getRepository(VoucherUsage::class)->findBy([
  1890.                 'voucherId' => $vouch["voucher_entity"]["id"],
  1891.                 'userId' => $id,
  1892.                 'isReallyUsed' => 1
  1893.             ]));
  1894.         }
  1895.         $data["command"] = $vouch;
  1896.         $payment_bill $this->entityManager->getRepository(PaymentBill::class)->findOneBy(['command' => $command->getId()]);
  1897.         if ($payment_bill) {
  1898.             $total_additionnal_fee intval($payment_bill->getAdditionalFeesTotalPrice());
  1899.         
  1900.             $data["command"]["additionnal_fee"] = $total_additionnal_fee;
  1901.             $data["command"]["promotion_total_pricing"] =
  1902.                 intval($data["command"]["promotion_food_pricing"])
  1903.                 + intval($data["command"]["promotion_shipping_pricing"])
  1904.                 + $total_additionnal_fee;
  1905.             $data["command"]["total_pricing"] = $data["command"]["promotion_total_pricing"];
  1906.             $data["command"]["preorder_total_pricing"] =
  1907.                 intval($data["command"]["preorder_food_pricing"])
  1908.                 + intval($data["command"]["preorder_shipping_pricing"])
  1909.                 + $total_additionnal_fee;
  1910.         
  1911.             $totalWithoutFee =
  1912.                 intval($data["command"]["promotion_total_pricing"]) - $total_additionnal_fee;
  1913.         
  1914.             $data["command"]["remise"] = (string) (
  1915.                 100 $this->getRemise(
  1916.                     intval($data["command"]["total_pricing"]) - $total_additionnal_fee,
  1917.                     $totalWithoutFee
  1918.                 )
  1919.             );
  1920.         }
  1921.         
  1922.         //check if rate
  1923.         $rating 0;
  1924.         $comment '';
  1925.         $repo $this->entityManager->getRepository(EntityDeliveryRating::class);
  1926.         $rate $repo->findOneBy([
  1927.             'commandId' => $command->getId()
  1928.         ]);
  1929.        try{
  1930.         if ($rate != null) {
  1931.             $rating $rate->getRating();
  1932.             $comment $rate->getComment();
  1933.         }
  1934.        }catch(Throwable $e){
  1935.        }
  1936.         $data["command"]["rating"] = $rating;
  1937.         $data["command"]["comment"] = $comment;
  1938.         return new Response($this->serializer->serialize($this->okResponseBlob($data), 'json'), 200);
  1939.     }
  1940.      /**
  1941.      * @Route("/subscription/command/details/v4/get", name="subscription_get_command_details", methods={"POST"})
  1942.      */
  1943.     public function getCommandDetailsByAdmin(Request $request){
  1944.         $json_data $request->getContent();
  1945.         $data json_decode($json_datatrue);
  1946.         $command_id $data["command_id"];
  1947.         $command =  $this->entityManager->getRepository(Command::class)->find(intval($command_id));
  1948.         $apiKey trim((string) $request->headers->get('X-API-KEY''')); // header canonical
  1949.         $expectedApiKey '7DCPbXNtTXMpifOcfOJCbXBQctN8cuII';
  1950.         if ($apiKey === '' || strlen($apiKey) !== strlen($expectedApiKey) || !hash_equals($expectedApiKey$apiKey)) {
  1951.             return new JsonResponse(['message' => 'Clé API invalide ou manquante'], 401);
  1952.         }
  1953.         if ($command == null) {
  1954.             return new Response($this->serializer->serialize($this->errorResponseBlob([]), 'json'), 200);
  1955.         }
  1956.         $vouch $this->madeUpCommandItemWithVoucher($command);
  1957.         if ($vouch["voucher_entity"] != []) {
  1958.             $vouch["voucher_entity"]["already_used_count"] = count($this->entityManager->getRepository(VoucherUsage::class)->findBy([
  1959.                 'voucherId' => $vouch["voucher_entity"]["id"],
  1960.                 'userId' => $command->getlientId(),
  1961.                 'isReallyUsed' => 1
  1962.             ]));
  1963.         }
  1964.         $data["command"] = $vouch;
  1965.         $payment_bill $this->entityManager->getRepository(PaymentBill::class)->findOneBy(['command' => $command->getId()]);
  1966.         if ($payment_bill) {
  1967.             $total_additionnal_fee intval($payment_bill->getAdditionalFeesTotalPrice());
  1968.             $data["command"]["additionnal_fee"] = $total_additionnal_fee;
  1969.             $data["command"]["promotion_total_pricing"] =
  1970.                 intval($data["command"]["promotion_food_pricing"])
  1971.                 + intval($data["command"]["promotion_shipping_pricing"])
  1972.                 + $total_additionnal_fee;
  1973.             $data["command"]["total_pricing"] = $data["command"]["promotion_total_pricing"];
  1974.             $data["command"]["preorder_total_pricing"] =
  1975.                 intval($data["command"]["preorder_food_pricing"])
  1976.                 + intval($data["command"]["preorder_shipping_pricing"])
  1977.                 + $total_additionnal_fee;
  1978.             $totalWithoutFee =
  1979.                 intval($data["command"]["promotion_total_pricing"]) - $total_additionnal_fee;
  1980.         
  1981.             $data["command"]["remise"] = (string) (
  1982.                 100 $this->getRemise(
  1983.                     intval($data["command"]["total_pricing"]) - $total_additionnal_fee,
  1984.                     $totalWithoutFee
  1985.                 )
  1986.             );
  1987.         }
  1988.         
  1989.         //check if rate
  1990.         $rating 0;
  1991.         $comment '';
  1992.         $repo $this->entityManager->getRepository(EntityDeliveryRating::class);
  1993.         $rate $repo->findOneBy([
  1994.             'commandId' => $command->getId()
  1995.         ]);
  1996.         if ($rate != null) {
  1997.             $rating $rate->getRating();
  1998.             $comment $rate->getComment();
  1999.         }
  2000.         $data["command"]["rating"] = $rating;
  2001.         $data["command"]["comment"] = $comment;
  2002.         return new Response($this->serializer->serialize($this->okResponseBlob($data), 'json'), 200);
  2003.    
  2004.     }
  2005.     /**
  2006.      * @Route("mobile/api/command/all/v4/get", name="user_mobile_v4_get_all_command", methods={"GET"})
  2007.      */
  2008. public function getApiAllCommandWithVoucherAction()
  2009. {
  2010.     $currentToken $this->get('security.token_storage')->getToken();
  2011.     $id $currentToken->getUser()->getId();
  2012.     $start date('Y-m-d'strtotime('-90 days'));
  2013.     $end date('Y-m-d'strtotime('+1 day'));
  2014.     $conn $this->entityManager->getConnection();
  2015.     $sql "
  2016.         SELECT *
  2017.         FROM command
  2018.         WHERE client_id = :id
  2019.           AND start_date BETWEEN :start AND :end
  2020.           AND restaurant_id IS NOT NULL
  2021.         ORDER BY last_update DESC
  2022.     ";
  2023.     $stmt $conn->prepare($sql);
  2024.     $stmt->execute([
  2025.         'id' => $id,
  2026.         'start' => $start,
  2027.         'end' => $end,
  2028.     ]);
  2029.     $rows $stmt->fetchAll();
  2030.     $result = ['commands' => []];
  2031.     foreach ($rows as $row) {
  2032.        
  2033.             $result['commands'][] =
  2034.                 $this->forMobileWithVoucherCommandToArrayFromRow($row);
  2035.         
  2036.     }
  2037.     
  2038.     return new Response(
  2039.         $this->serializer->serialize(
  2040.             $this->okResponseBlob($result),
  2041.             'json'
  2042.         )
  2043.     );
  2044. }
  2045.     /**
  2046.      * @Route("mobile/api/command/v4/get", name="user_mobile_v4_get_command", methods={"POST"})
  2047.      */
  2048.     public function getApiCommandWithVoucherAction()
  2049.     {
  2050.         $em $this->entityManager;
  2051.     
  2052.         $currentToken $this->get('security.token_storage')->getToken();
  2053.         $id = (int) $currentToken->getUser()->getId();
  2054.     
  2055.         $command_array = [
  2056.             'commands' => []
  2057.         ];
  2058.     
  2059.         $batchSize 100;
  2060.         $offset    0;
  2061.         $today     date('Y-m-d');
  2062.     
  2063.         do {
  2064.             /** -------------------------
  2065.              *  Fetch IDs only
  2066.              *  -------------------------
  2067.              */
  2068.             $commandIds $em->createQuery(
  2069.                 'SELECT c.id
  2070.                  FROM App:Command c
  2071.                  WHERE c.clientId = :id
  2072.                  AND (
  2073.                      c.startDate = :startDate
  2074.                      OR (c.startDate < :startDate AND c.state < :deliveredState)
  2075.                  )
  2076.                  AND c.order_type IS NULL
  2077.                  ORDER BY c.lastUpdate DESC'
  2078.             )
  2079.             ->setParameter('id'$id)
  2080.             ->setParameter('startDate'$today)
  2081.             ->setParameter('deliveredState'3)
  2082.             ->setFirstResult($offset)
  2083.             ->setMaxResults($batchSize)
  2084.             ->getScalarResult();
  2085.     
  2086.             foreach ($commandIds as $row) {
  2087.                 try {
  2088.                     /** -------------------------
  2089.                      *  Load command
  2090.                      *  -------------------------
  2091.                      */
  2092.                     $command $em->getRepository(Command::class)->find($row['id']);
  2093.                     if (!$command) {
  2094.                         continue;
  2095.                     }
  2096.     
  2097.                     $tmp $this->forMobileWithVoucherCommandToArray($command);
  2098.     
  2099.                     /** -------------------------
  2100.                      *  Payment bill
  2101.                      *  -------------------------
  2102.                      */
  2103.                     $paymentBill $em->getRepository(PaymentBill::class)
  2104.                         ->findOneBy(['command' => $command->getId()]);
  2105.     
  2106.                         
  2107.                     if ($paymentBill) {
  2108.                         $additionalFee intval($paymentBill->getAdditionalFeesTotalPrice());
  2109.                         $tmp['additionnal_fees'] = $additionalFee;
  2110.                         $tmp['promotion_total_pricing'] =
  2111.                             intval($tmp['promotion_total_pricing']) + $additionalFee;
  2112.                         $tmp['total_pricing'] =
  2113.                             intval($tmp['total_pricing']) + $additionalFee;
  2114.                         $tmp['preorder_total_pricing'] =
  2115.                             intval($tmp['preorder_total_pricing']) + $additionalFee;
  2116.                     }
  2117.                     $command_array['commands'][] = $tmp;
  2118.     
  2119.                 } catch (\Throwable $e) {
  2120.                     $this->get('logger')->info(
  2121.                         'Command ID ' $row['id'] . ' skipped: ' $e->getMessage()
  2122.                     );
  2123.                     continue;
  2124.                 }
  2125.             }
  2126.     
  2127.             $em->clear();
  2128.             $offset += $batchSize;
  2129.     
  2130.         } while (count($commandIds) === $batchSize);
  2131.     
  2132.         return new Response(
  2133.             $this->serializer->serialize(
  2134.                 $this->okResponseBlob($command_array),
  2135.                 'json'
  2136.             )
  2137.         );
  2138.     }
  2139.     
  2140.     /**
  2141.      * @Route("mobile/api/command/delivery_rating_pending/v4/get", name="user_mobile_v4_get_delivery_rating_pending", methods={"POST"})
  2142.     */
  2143.     public function getDeliveryRatingPending(Request $request){
  2144.         $currentToken $this->get('security.token_storage')->getToken();
  2145.         $json_data $request->getContent(); 
  2146.         $data json_decode($json_data,true);
  2147.         $delivery_rating_pending = [
  2148.             "command_id" => null,
  2149.             "delivery_man_image" => null,
  2150.             "delivery_man_name" => null,
  2151.             "articles" => null,
  2152.             "seller_name" => null,
  2153.             "seller_image" => null,
  2154.             "delivery_rating" => 3,
  2155.             "article_rating" => 3,
  2156.             "article_comment" => "",
  2157.             "delivery_comment" => "",
  2158.             "speedRating" => 3,
  2159.             "respectOfGeolocation" => 3,
  2160.             "attidudeOfDeliveryMan" => 3,
  2161.             "groomingOfDeliveryMan" => 3
  2162.         ];
  2163.         $foods =[];
  2164.         if(isset($data['command_id'])){
  2165.             $delivery_rating_pending['command_id']=$data['command_id'];
  2166.             $command $this->entityManager->getRepository(Command::class)->find($data['command_id']);
  2167.             if($command ){   
  2168.               if($command->getState()==3){
  2169.                 $livreur $this->entityManager->getRepository(Livreur::class)->find($command->getLivreurId());
  2170.                 if($livreur){
  2171.                     $delivery_rating_pending['delivery_man_image'] = "https://kaba-delivery-pictures-store.s3.eu-west-3.amazonaws.com/employee_picture/".$livreur->getProfile()??"";
  2172.                     $delivery_rating_pending['delivery_man_name'] = $livreur->getName();
  2173.                 }else{
  2174.                     
  2175.                     return new Response($this->serializer->serialize($this->errorResponseBlob([]), 'json'));
  2176.                 }
  2177.                 foreach ($command->getFoodCommand() as $i => $food_command) {
  2178.                     $food $food_command["food_entity"];
  2179.                     array_push($foods,['name'=>$food['name'],'id'=>$food['id'],'rating'=>3]);
  2180.                 }       
  2181.                 $delivery_rating_pending['articles'] =$foods;      
  2182.                 $restaurant $this->entityManager->getRepository(RestaurantConfig::class)->find($command->getRestaurantId());
  2183.                 $delivery_rating_pending['seller_name'] =$restaurant->getName();
  2184.                 $delivery_rating_pending['seller_image'] =$restaurant->getPic();
  2185.                 return new Response($this->serializer->serialize($this->okResponseBlob($delivery_rating_pending), 'json'));
  2186.               }else{
  2187.                 return new Response($this->serializer->serialize($this->errorResponseBlob("Order is not delivered"), 'json'));
  2188.               }
  2189.             }else{
  2190.                 return new Response($this->serializer->serialize($this->errorResponseBlob("Command null"), 'json'));
  2191.             }
  2192.         }else{
  2193.             return new Response($this->serializer->serialize($this->errorResponseBlob([]), 'json'));
  2194.         }
  2195.     }
  2196.     /**
  2197.      * @Route("mobile/api/command/rating/v4/get", name="user_mobile_v4_get_rating", methods={"GET"})
  2198.     */
  2199.     public function getApiRatingAction()
  2200.     {
  2201.         $repo $this->entityManager->getRepository(EntityDeliveryRating::class);
  2202.         $ratings $this->entityManager->createQuery(
  2203.             '  SELECT 
  2204.         r.speedRating AS speedRating,
  2205.         r.respectOfGeolocation AS respectOfGeolocation,
  2206.         r.attidudeOfDeliveryMan AS attidudeOfDeliveryMan,
  2207.         r.groomingOfDeliveryMan AS groomingOfDeliveryMan
  2208.          FROM App\V4Bundle\Entity\DeliveryRating r'
  2209.           )->getArrayResult();
  2210.          $speedSum 0;
  2211.         $geoSum 0;
  2212.         $attitudeSum 0;
  2213.         $appearanceSum 0;
  2214.         $speedCount 0;
  2215.         $geoCount 0;
  2216.         $attitudeCount 0;
  2217.         $appearanceCount 0;
  2218.         foreach ($ratings as $rating) {
  2219.             if ($rating['speedRating'] != 0) {
  2220.                 $speedSum += $rating['speedRating'];
  2221.                 $speedCount++;
  2222.             }
  2223.         
  2224.             if ($rating['respectOfGeolocation'] != 0) {
  2225.                 $geoSum += $rating['respectOfGeolocation'];
  2226.                 $geoCount++;
  2227.             }
  2228.         
  2229.             if ($rating['attidudeOfDeliveryMan'] != 0) {
  2230.                 $attitudeSum += $rating['attidudeOfDeliveryMan'];
  2231.                 $attitudeCount++;
  2232.             }
  2233.         
  2234.             if ($rating['groomingOfDeliveryMan'] != 0) {
  2235.                 $appearanceSum += $rating['groomingOfDeliveryMan'];
  2236.                 $appearanceCount++;
  2237.             }
  2238.         }
  2239.         
  2240.         $speedAvg $speedCount $speedSum $speedCount 0;
  2241.         $geoAvg $geoCount $geoSum $geoCount 0;
  2242.         $attitudeAvg $attitudeCount $attitudeSum $attitudeCount 0;
  2243.         $appearanceAvg $appearanceCount $appearanceSum $appearanceCount 0;
  2244.         $speedAvg max($speedAvg3);
  2245.         $geoAvg max($geoAvg3);
  2246.         $attitudeAvg max($attitudeAvg3);
  2247.         $appearanceAvg max($appearanceAvg3);
  2248.         $averages = [];
  2249.         if ($speedCount 0$averages[] = $speedAvg;
  2250.         if ($geoCount 0$averages[] = $geoAvg;
  2251.         if ($attitudeCount 0$averages[] = $attitudeAvg;
  2252.         if ($appearanceCount 0$averages[] = $appearanceAvg;
  2253.         $finalRating count($averages) > array_sum($averages) / count($averages) : 0;
  2254.         $data = [
  2255.             "speed" => round($speedAvg1),
  2256.             "geolocation" => round($geoAvg1),
  2257.             "attitude" => round($attitudeAvg1),
  2258.             "appearance" => round($appearanceAvg1),
  2259.             "final" => round($finalRating1),
  2260.             "count" => $speedCount
  2261.         ];
  2262.         return new JsonResponse($data);
  2263.     }
  2264.     
  2265.     /**
  2266.      * @Route("mobile/api/command/v4/rate", name="user_mobile_v4_rate_command", methods={"POST"})
  2267.     */
  2268.     public function commandDeliveryManRateAction(Request $request)
  2269.     {
  2270.         $json_data $request->getContent();
  2271.         $data json_decode($json_datatrue);
  2272.         $currentToken $this->get('security.token_storage')->getToken();
  2273.         $id $currentToken->getUser()->getId();
  2274.         if ($id != null) {
  2275.             if (
  2276.                 isset($data["command_id"]) && $data["command_id"] != null 
  2277.              
  2278.             ) {
  2279.                 /**
  2280.                  * @var Command $command
  2281.                  */
  2282.                 $command $this->entityManager->getRepository(Command::class)->find(intval($data["command_id"]));
  2283.                 if ($command != null) {
  2284.                     /*check if already rated*/
  2285.                     $em =$this->entityManager;
  2286.                     $repo $this->entityManager->getRepository(EntityDeliveryRating::class);
  2287.                     $rate $repo->findOneBy(['commandId' => $command->getId()]);
  2288.                     if ($rate != null) {
  2289.                         $rate->setDeliveryRating(intval($data["delivery_rating"]));
  2290.                         if (isset($data["delivery_comment"]) && $data["delivery_comment"] != null) {
  2291.                             $rate->setDeliveryComment($data["delivery_comment"]);
  2292.                         }
  2293.                         $rate->setCreatedAt(strtotime(date('Y-m-d H:i:s')));
  2294.                     } else {
  2295.                         $rating = new EntityDeliveryRating();
  2296.                         $rating->setUserId($id);
  2297.                         $rating->setCommandId(intval($data["command_id"]));
  2298.                         $rating->setLivreurId($command->getLivreurId());
  2299.                         $rating->setDeliveredAt($command->getEndOfDelivery());
  2300.                         $rating->setDeliveryRating(intval($data["delivery_rating"]));
  2301.                         if (isset($data["command_id"]) && $data["command_id"] != null) {
  2302.                             $rating->setCommandId($data["command_id"]);
  2303.                         }
  2304.                         if (isset($data["delivery_rating"]) && $data["delivery_rating"] != null) {
  2305.                             $rating->setDeliveryRating($data["delivery_rating"]);
  2306.                         }
  2307.                         
  2308.                         if(isset($data['articles'])&& $data['articles']!=null){
  2309.                             $rating->setArticlesRating($data['articles']);
  2310.                         }
  2311.                         
  2312.                         if (isset($data["article_comment"]) && $data["article_comment"] != null) {
  2313.                             $rating->setArticleComment($data["article_comment"]);
  2314.                         }
  2315.                         
  2316.                         if (isset($data["delivery_comment"]) && $data["delivery_comment"] != null) {
  2317.                             $rating->setDeliveryComment($data["delivery_comment"]);
  2318.                         }
  2319.                         
  2320.                         if (isset($data["speedRating"]) && $data["speedRating"] != null) {
  2321.                             $rating->setSpeedRating($data["speedRating"]);
  2322.                         }
  2323.                         
  2324.                         if (isset($data["respectOfGeolocation"]) && $data["respectOfGeolocation"] != null) {
  2325.                             $rating->setRespectOfGeolocation($data["respectOfGeolocation"]);
  2326.                         }
  2327.                         
  2328.                         if (isset($data["attidudeOfDeliveryMan"]) && $data["attidudeOfDeliveryMan"] != null) {
  2329.                             $rating->setAttidudeOfDeliveryMan($data["attidudeOfDeliveryMan"]);
  2330.                         }
  2331.                         
  2332.                         if (isset($data["groomingOfDeliveryMan"]) && $data["groomingOfDeliveryMan"] != null) {
  2333.                             $rating->setGroomingOfDeliveryMan($data["groomingOfDeliveryMan"]);
  2334.                         }
  2335.                         
  2336.                         
  2337.                         $rating->setRestaurantId($command->getRestaurantId());
  2338.                         $rating->setCreatedAt(strtotime(date('Y-m-d H:i:s')));
  2339.                         $em->persist($rating);
  2340.                         // update command
  2341.                         $command->setHaveRating(true);
  2342.                         $em->flush();
  2343.                         $livreur $this->entityManager
  2344.                         ->getRepository(Livreur::class)
  2345.                         ->find($rating->getLivreurId());
  2346.                     
  2347.                     $new_rating = (intval($data["attidudeOfDeliveryMan"]) + intval($data["groomingOfDeliveryMan"])) / 2;                   
  2348.                     $deliveries_rating $this->entityManager
  2349.                         ->getRepository(EntityDeliveryRating::class)
  2350.                         ->findBy(['livreurId' => $livreur->getId()]);                  
  2351.                     $total_rating 0;
  2352.                     $valid_count 0;
  2353.                     
  2354.                     if ($deliveries_rating && count($deliveries_rating) > 0) {
  2355.                         foreach ($deliveries_rating as $r) {
  2356.                             if ($r->getDeliveryRating() !== null) {
  2357.                                 $total_rating += $r->getDeliveryRating();
  2358.                                 $valid_count++;
  2359.                             }
  2360.                         }
  2361.                         $total_livreur_rating = ($total_rating $new_rating) / ($valid_count 1);
  2362.                         $livreur->setRating($total_livreur_rating);
  2363.                     
  2364.                     } else {
  2365.                     
  2366.                         $livreur->setRating($new_rating);
  2367.                     }
  2368.                     
  2369.                     $em->persist($livreur);
  2370.                     $em->flush();
  2371.                     
  2372.                     //food rating 
  2373.                     $query $this->entityManager->createQuery('
  2374.                         SELECT r FROM App\V4Bundle\Entity\DeliveryRating r 
  2375.                         WHERE r.restaurantId = :id
  2376.                     ')
  2377.                     ->setParameter('id', (int) $command->getRestaurantId());
  2378.                     $rates $query->getResult();
  2379.                     $ratings json_decode($this->serializer->serialize($rates,'json'), true);
  2380.                     $articles $data['articles'];
  2381.                     if(count($articles)==1){
  2382.                         if($ratings !=null && count($ratings)>0){
  2383.                             $articles $data['articles'];
  2384.                                 $total_rating=0;
  2385.                                 $total_count_rating=0;
  2386.                             
  2387.                                 foreach($ratings as $rating){
  2388.                                     if($rating["articlesRating"]!=null && count($rating["articlesRating"])>0){
  2389.                                         foreach ($rating["articlesRating"] as $art) {
  2390.                                             if($data['articles'][0]['id']==$art['id']){
  2391.                                                 if($art['rating']!=0){
  2392.                                                     $total_rating+=$art['rating'];
  2393.                                                     $total_count_rating++;
  2394.                                                     break;
  2395.                                                 }
  2396.                                             }
  2397.                                         }
  2398.                                     }else{
  2399.                                         continue;
  2400.                                     }
  2401.                                 }
  2402.                                 $total_article_rating = ($total_rating+$data['articles'][0]['rating'])/($total_count_rating+1);
  2403.                                 $article_entity =$this->entityManager->getRepository(Food::class)->find($data['articles'][0]['id']);
  2404.                                 $article_entity->setRating(round($total_article_rating1));
  2405.                                 $em->persist($article_entity);
  2406.                                 $em->flush();
  2407.                             
  2408.                         }else{
  2409.                                 $article_entity =$this->entityManager->getRepository(Food::class)->find($data['articles'][0]['id']);
  2410.                                 $article_entity->setRating($data['articles'][0]['rating']);
  2411.                                 $em->persist($article_entity);
  2412.                                 $em->flush();
  2413.                         }
  2414.                     }
  2415.                     }
  2416.                     return new JsonResponse($this->serializer->serialize($this->okResponseBlob(null), 'json'));
  2417.                 } else {
  2418.                     return new JsonResponse($this->serializer->serialize($this->errorResponseBlob("No command"), 'json'));
  2419.                 }
  2420.             } else {
  2421.                 return new JsonResponse($this->$this->serializer->serialize($this->errorResponseBlob("Invalid Parameters"'json')));
  2422.             }
  2423.         } else {
  2424.             return new JsonResponse($this->serializer->serialize($this->errorResponseBlob("Invalid token"), 'json'));
  2425.         }
  2426.     }
  2427.     /**
  2428.      * @Route("mobile/api/command/v4/rate/test", name="user_mobile_v4_rate_command_test", methods={"POST"})
  2429.     */
  2430.     public function testRate(){
  2431.         $currentToken $this->get('security.token_storage')->getToken();
  2432.         $id $currentToken->getUser()->getId();
  2433.         $articleId 561;
  2434.         $em $this->entityManager;
  2435.         $conn $em->getConnection();
  2436.         $sql "
  2437.         SELECT *
  2438.         FROM delivery_rating r
  2439.         WHERE r.restaurant_id = :restaurantId
  2440.             AND r.articles_rating IS NOT NULL
  2441.             AND r.articles_rating != ''
  2442.             AND JSON_CONTAINS(r.articles_rating, :articleJson, '$') = 1
  2443.     ";
  2444.     $stmt $conn->prepare($sql);
  2445.     $stmt->execute([
  2446.         'restaurantId' => 15,
  2447.         'articleJson'  => json_encode(["id" => $articleId]),
  2448.     ]);
  2449.     
  2450.      $ratings $stmt->fetchAllAssociative();
  2451.             $res['rate_count'] = count($ratings);
  2452.             $article_comments = [];
  2453.             foreach ($ratings as $rating) {
  2454.                 $comment = [
  2455.                     'rating' => 0,
  2456.                     'comment' => $rating['article_comment'],
  2457.                     'client_name'=>"",
  2458.                     'client_pic' =>'',
  2459.                 ];
  2460.                 if($rating['articles_rating']!=null){
  2461.                     $articles =json_decode($rating['articles_rating'],true);
  2462.                     for($i=0;$i<count($articles); $i++){
  2463.                         if($articles[$i]['id']==$articleId){
  2464.                             $comment['rating'] = $articles[$i]['rating'];
  2465.                             break;
  2466.                         }
  2467.                     }
  2468.                 }
  2469.                 $command $em->getRepository(Command::class)->find($rating['command_id']);
  2470.                 $client $em->getRepository(Client::class)->find($command->getClientId());
  2471.                 if ($client != null) {
  2472.                     $comment['client_name'] = $client->getNickname();
  2473.                     $comment['client_pic'] = $client->getProfilePicture();
  2474.                     if($comment['comment']!=null){
  2475.                         array_push($article_comments$comment);
  2476.                     }
  2477.                 }
  2478.             }
  2479.             return new JsonResponse($article_comments);
  2480.     
  2481. }
  2482. /**
  2483.  * @Route("/subscription/user-transaction/get", name="subscription_user_transaction", methods={"GET"})
  2484.  */
  2485. public function SubscriptionGetUserTransaction(Request $request): JsonResponse
  2486. {
  2487.     $apiKey trim((string) $request->headers->get('X-API-KEY''')); // header canonical
  2488.     $expectedApiKey '7DCPbXNtTXMpifOcfOJCbXBQctN8cuII';
  2489.     if ($apiKey === '' || strlen($apiKey) !== strlen($expectedApiKey) || !hash_equals($expectedApiKey$apiKey)) {
  2490.         return new JsonResponse(['message' => 'Clé API invalide ou manquante'], 401);
  2491.     }
  2492.    $data json_decode($request->getContent(), true) ?? [];
  2493.     $transaction $this->entityManager->getRepository(Transaction::class)->findOneBy(
  2494.         ['userId' => $data['user_id'],'transactionMotifId'=>2],
  2495.         ['createdDate' => 'DESC'
  2496.     );
  2497.     if (!$transaction) {
  2498.         return new JsonResponse(['transaction' => null], 200);
  2499.     }
  2500.     $json $this->serializer->serialize($transaction'json');
  2501.     return new JsonResponse(['transaction' => json_decode($jsontrue)], 200);
  2502. }
  2503.     public function createPaymentBill($data$command_id)
  2504.     {
  2505.         $command $this->entityManager->getRepository(Command::class)->find($command_id);
  2506.         $payment_bill = new PaymentBill();
  2507.         $payment_bill
  2508.             ->setShippingPricing(isset($data["shipping_pricing"]) ? $data["shipping_pricing"] : -1)
  2509.             ->setPromotionShippingPricing(isset($data["promotion_shipping_pricing"]) ? $data["promotion_shipping_pricing"] : -1)
  2510.             ->setPromotionPricing(isset($data["promotion_pricing"]) ? $data["promotion_pricing"] : -1)
  2511.             ->setCommandPricing(isset($data["command_pricing"]) ? $data["command_pricing"] : -1)
  2512.             ->setRemise(isset($data["remise"]) ? $data["remise"] : -1)
  2513.             ->setTotalPricing(isset($data["total_pricing"]) ? $data["total_pricing"] : -1)
  2514.             ->setTotalNormalPricing(isset($data["total_normal_pricing"]) ? $data["total_normal_pricing"] : -1)
  2515.             ->setAccountBalance(isset($data["account_balance"]) ? $data["account_balance"] : -1)
  2516.             ->setOutOfRange(isset($data["out_of_range"]) ? $data["out_of_range"] : false)
  2517.             ->setPayAtDelivery(isset($data["pay_at_delivery"]) ? $data["pay_at_delivery"] : false)
  2518.             ->setPrepaid(isset($data["prepayed"]) ? $data["prepayed"] : false)
  2519.             ->setTrustful(isset($data["trustful"]) ? $data["trustful"] : -1)
  2520.             ->setMaxPay(isset($data["max_pay"]) ? $data["max_pay"] : -1)
  2521.             ->setCookingTime(isset($data["cooking_time"]) ? $data["cooking_time"] : -1)
  2522.             ->setCanPreorder(isset($data["can_preorder"]) ? $data["can_preorder"] : -1)
  2523.             ->setDiscount(isset($data["discount"]) ? $data["discount"] : "")
  2524.             ->setOpenType(isset($data["open_type"]) ? $data["open_type"] : -1)
  2525.             ->setWorkingHour(isset($data["working_hour"]) ? $data["working_hour"] : "")
  2526.             ->setReason(isset($data["reason"]) ? $data["reason"] : "")
  2527.             ->setDeliveryFrames(isset($data["delivery_frames"]) && is_array($data["delivery_frames"]) ? $data["delivery_frames"] : null)
  2528.             ->setBillBuilt(isset($data["is_bill_built"]) ? $data["is_bill_built"] : false)
  2529.             ->setCheckedOpen(isset($data["checked_open"]) ? $data["checked_open"] : false)
  2530.             ->setTotalPreorderPricing(isset($data["total_preorder_pricing"]) ? $data["total_preorder_pricing"] : -1)
  2531.             ->setKabaPoint(isset($data["kaba_point"]) ? $data["kaba_point"] : ["value" => null])
  2532.             ->setEligibleVouchers(isset($data["eligible_vouchers"]) ? $data["eligible_vouchers"] : ["value" => null])
  2533.             ->setAdditionalFees(isset($data["additional_fees"]) ? $data["additional_fees"] : ["value" => null])
  2534.             ->setAdditionalFeesTotalPrice(isset($data["additional_fees_total_price"]) ? $data["additional_fees_total_price"] : -1)
  2535.             ->setCommandId($command);
  2536.         $this->entityManager->persist($payment_bill);
  2537.         $this->entityManager->flush();
  2538.         return new Response("Success"200);
  2539.     }
  2540.     private function madeUpCommandItemWithVoucher(Command $command)
  2541.     {
  2542.         $tmp = [];
  2543.         $type 1;
  2544.         $user =  $this->entityManager->getRepository(Client::class)->find($command->getClientId());
  2545.         if ($user != null) {
  2546.             $type filter_var($user->getUsername(), FILTER_VALIDATE_EMAIL) ? 1;
  2547.         }
  2548.         $shipping_address $command->getShippingAddress();
  2549.         $restaurant =  $this->entityManager->getRepository(RestaurantConfig::class)->find($command->getRestaurantId());
  2550.         $addresss =  $this->entityManager->getRepository(Adresses::class)->find(intval($shipping_address["id"]));
  2551.         $address $this->addressForMobileToArray($addresss);
  2552.         $standard_price $this->shippingPricing($restaurant->getId(), $address$type);
  2553.         $billing intval($standard_price["billing"]);
  2554.         $promotion_billing intval($command->getShippingPricing());
  2555.         $voucher_billing 0;
  2556.         $voucher_food_price 0;
  2557.         $is_voucher_used 0;
  2558.         $is_food_voucher_used 0;
  2559.         $is_billing_voucher_used 0;
  2560.         $tmp["food_list"] = [];
  2561.         $state intval($command->getState());
  2562.         if ($state == || $state == 3) {
  2563.             $livreur $this->entityManager->getRepository(Livreur::class)->find($command->getLivreurId());
  2564.             if ($livreur != null) {
  2565.                 $tmp["livreur"] = [];
  2566.                 $tmp["livreur"]["id"] = $livreur->getId();
  2567.                 $tmp["livreur"]["name"] = $livreur->getName();
  2568.                 $tmp["livreur"]["workcontact"] = $livreur->getWorkContact();
  2569.                 $pic '';
  2570.                 $employee $this->entityManager->getRepository(Employee::class)->find(intval($livreur->getEmployeeId()));
  2571.                 if ($employee != null) {
  2572.                     $pic 'employee_picture/' $employee->getFileName();
  2573.                 }
  2574.                 $tmp["livreur"]["pic"] = $pic;
  2575.             }
  2576.         }
  2577.         $price_remise 0;
  2578.         $price_command 0;
  2579.         $is_promo 0;
  2580.         $is_preorder 0;
  2581.         foreach ($command->getFoodCommand() as $i => $food_command) {
  2582.             $food $food_command["food_entity"];
  2583.             if ($i == 0) {
  2584.                 $shipping $food_command["food_shipping"];
  2585.                 if ($shipping["is_shipping_promo"] == 1) {
  2586.                     $is_promo 1;
  2587.                     $billing $shipping["shipping_pricing"];
  2588.                 }
  2589.             }
  2590.             $price_command += intval($food["price"]) * intval($food_command["quantity"]);
  2591.             if ($food["promotion"] == 1) {  /*if food is in promotion*/
  2592.                 $price_remise += intval($food["promotion_price"]) * intval($food_command["quantity"]);
  2593.                 $is_promo 1;
  2594.             } else {
  2595.                 $price_remise += intval($food["price"]) * intval($food_command["quantity"]);
  2596.             }
  2597.             $food["quantity"] = $food_command["quantity"];
  2598.             $food["promotion_price"] = '' $food["promotion_price"];
  2599.             array_push($tmp["food_list"], $food);
  2600.         }
  2601.         if ($command->getPreOrder() == 1) {
  2602.             $price_remise $price_command;
  2603.             $is_preorder 1;
  2604.         }
  2605.         $total_without_remise $price_command $billing;
  2606.         $total_with_remise $price_remise $promotion_billing;
  2607.         $tmp["kaba_point_used_amount"] = 0;
  2608.         if ($command->getKabaPoint() != null) {
  2609.             $is_promo 1;
  2610.             $tmp["kaba_point_used_amount"] = $command->getKabaPointAmount();
  2611.         }
  2612.         $tmp["id"] = $command->getId();
  2613.         $tmp["foods_count"] = count($command->getFoodCommand());
  2614.         $tmp["is_payed_at_arrival"] = $command->getPayAtDelivery();
  2615.         $tmp["state"] = $state;
  2616.         $tmp["infos"] = $command->getInfos();
  2617.         $tmp["restaurant_entity"] = [];
  2618.         $tmp["restaurant_entity"]["id"] = $restaurant->getId();
  2619.         $tmp["restaurant_entity"]["name"] = $restaurant->getName();
  2620.         $tmp["restaurant_entity"]["pic"] = '/' $this->getParameter('rp') . '/' $restaurant->getPic();
  2621.         $tmp["remise"] = '' . (100 $this->getRemise($total_without_remise$total_with_remise));
  2622.         $tmp["out_of_range"] = $standard_price["out_of_range"];
  2623.         $tmp["shipping_address"] = $shipping_address;
  2624.         if (isset($tmp["shipping_address"]["user"])) {
  2625.             $tmp["shipping_address"]["user"] = [];
  2626.         }
  2627.         $tmp["is_promotion"] = $is_promo;
  2628.         $tmp["is_preorder"] = $is_preorder;
  2629.         $tmp["shipping_pricing"] = intval($billing);
  2630.         $tmp["food_pricing"] = intval($price_command);
  2631.         $tmp["total_pricing"] = intval($billing $price_command);
  2632.         $tmp["promotion_shipping_pricing"] = intval($promotion_billing);
  2633.         $tmp["promotion_food_pricing"] = intval($price_remise);
  2634.         $tmp["promotion_total_pricing"] = intval($promotion_billing $price_remise);
  2635.         $tmp["preorder_shipping_pricing"] = intval($promotion_billing);
  2636.         $tmp["preorder_food_pricing"] = intval($price_command);
  2637.         $tmp["preorder_total_pricing"] = intval($promotion_billing $price_command);
  2638.         $tmp["voucher_entity"] = [];
  2639.         $voucher_datas $this->processVoucherDatas($command$promotion_billing$billing$price_remise);
  2640.         if ($voucher_datas["is_voucher_used"]) {
  2641.             $tmp["is_promotion"] = 1;
  2642.             $tmp["promotion_food_pricing"] = $voucher_datas["price_remise"];
  2643.             $tmp["promotion_shipping_pricing"] = $voucher_datas["shipping_pricing"];
  2644.             $tmp["promotion_total_pricing"] = intval($voucher_datas["price_remise"]) + intval($voucher_datas["shipping_pricing"]);
  2645.             $tmp["remise"] = '' . (100 $this->getRemise($total_without_remise$tmp["promotion_total_pricing"]));
  2646.             $tmp["is_voucher_used"] = 1;
  2647.             if ($voucher_datas["voucher_id"] != null) {
  2648.                 $voucher $this->entityManager->getRepository(Voucher::class)->find($voucher_datas["voucher_id"]);
  2649.                 if ($voucher != null) {
  2650.                     $tmp["voucher_entity"] = $this->voucherToArrayLite($voucher);
  2651.                     $tmp["voucher_entity"]["id"] = $voucher->getId();
  2652.                 }
  2653.             }
  2654.         }
  2655.         $tmp["preorder"] = $command->getPreOrder();
  2656.         $tmp["preorder_hour"] = null;
  2657.         if ($command->getPreOrder() == 1) {
  2658.             $preorder_hour $this->entityManager->getRepository(PreorderCommandDetails::class)->findOneBy([
  2659.                 'commandId' => $command->getId()
  2660.             ]);
  2661.             if ($preorder_hour != null) {
  2662.                 $tmp["preorder_hour"]["start"] = $preorder_hour->getStart();
  2663.                 $tmp["preorder_hour"]["end"] = $preorder_hour->getEnd();
  2664.                 $tmp["preorder_discount"] = $preorder_hour->getDiscount();
  2665.             }
  2666.         }
  2667.         $tmp["passphrase"] = $command->getPassPhrase();
  2668.         $tmp["last_update"] = strtotime($command->getLastUpdate());
  2669.         $tmp["reason"] = $command->getReason();
  2670.         $haveBonus $this->entityManager->getRepository(PayBonus::class)->findOneBy(["clientId" => $command->getClientId(), "commandId" => $command->getId()]);
  2671.         if ($haveBonus != null && $haveBonus->getOfferType() == '1') {
  2672.             $tmp["is_promotion"] = 1;
  2673.             $tmp["promotion_total_pricing"] -= $tmp["promotion_shipping_pricing"];
  2674.             $tmp["promotion_shipping_pricing"] = 0;
  2675.             $tmp["preorder_total_pricing"] -= $tmp["preorder_shipping_pricing"];
  2676.             $tmp["preorder_shipping_pricing"] = 0;
  2677.             $tmp["without_voucher_promotion_shipping_pricing"] = 0;
  2678.         }
  2679.         return $tmp;
  2680.     }
  2681.     private function getRestaurantId($food_command)
  2682.     {
  2683.         if (!($food_command != null && count($food_command) > 0))
  2684.             return -1;
  2685.         $food_id $food_command[0]["food_id"];
  2686.         $bdd_food =  $this->entityManager->getRepository(Food::class)->find(intval($food_id));
  2687.         return $bdd_food->getRestaurantId();
  2688.     }
  2689.     private function getAdress($shipping_address_id)
  2690.     {
  2691.         if ($shipping_address_id == null)
  2692.             return -1;
  2693.         $address $this->entityManager->getRepository(Adresses::class)->find($shipping_address_id);
  2694.         if ($address == null)
  2695.             return -1;
  2696.         $address_in_array $this->addressForMobileToArray($address);
  2697.         return $address_in_array;
  2698.     }
  2699.     private function getCommandDetails2($food_command$restaurant_id$address$preorder$voucher_id null$user_id null$use_kaba_point false)
  2700.     {
  2701.         $price 0;
  2702.         $without_promotion_price 0;
  2703.         $without_promotion_billing 0;
  2704.         $food_litteral "";
  2705.         $haveBillingDiscount false;
  2706.         $is_voucher_used false;
  2707.         $is_food_voucher_used false;
  2708.         $is_billing_voucher_used false;
  2709.         $voucher_billing 0;
  2710.         $voucher_food_price 0;
  2711.         $voucher_owner_food_price_gain 0;
  2712.         $voucher_owner_billing_gain 0;
  2713.         $check_voucher_valid $this->checkIfVoucherValid($user_id$voucher_id);
  2714.         $check_voucher_owners =  $this->entityManager->getRepository(VoucherOwner::class)->findOneBy([
  2715.             'voucherId' => $voucher_id
  2716.         ]);
  2717.         $kabaPoint null;
  2718.         $type 1;
  2719.         $user =  $this->entityManager->getRepository(Client::class)->find($user_id);
  2720.         if ($user != null)
  2721.             $type filter_var($user->getUsername(), FILTER_VALIDATE_EMAIL) ? 1;
  2722.         $standard_price $this->shippingPricing($restaurant_id$address$type);
  2723.         $restaurant $this->entityManager->getRepository(RestaurantConfig::class)->find($restaurant_id);
  2724.         $billing $standard_price["billing"];
  2725.         $voucher_billing intval($billing);
  2726.         $is_voucher_on_billing_already_applyed false;
  2727.         $without_promotion_billing $standard_price["billing"];
  2728.         $without_promotion_billing_for_email $standard_price["email_account_billing"];
  2729.         $without_promotion_billing_for_PhoneNumber $standard_price["phoneNumber_account_billing"];
  2730.         $extra_shipping_pricing intval($standard_price["email_account_billing"]) - intval($standard_price["phoneNumber_account_billing"]);
  2731.         $with_discount_billing_for_email $standard_price["email_account_billing"];
  2732.         $with_discount_billing_for_PhoneNumber $standard_price["phoneNumber_account_billing"];
  2733.         $voucherBillingForPhoneNumber intval($standard_price["phoneNumber_account_billing"]);
  2734.         $voucherBillingForEmail intval($standard_price["email_account_billing"]);
  2735.         $preorderBillingForPhoneNumber intval($standard_price["email_account_billing"]);
  2736.         $preorderBillingForEmail intval($standard_price["phoneNumber_account_billing"]);
  2737.         $is_shipping_promo 0;
  2738.         if ($restaurant != null && $address != null) {
  2739.             $distance $this->getDistance(
  2740.                 $address["location"],
  2741.                 $restaurant->getLocation()
  2742.             );
  2743.             $the_distance $distance;
  2744.             $promotion $this->checkEligiblePromotionV2($the_distance$restaurant_id$food_command$user);
  2745.             if ($promotion["found"] == true) {
  2746.                 $billing $promotion["billing"];
  2747.                 $with_discount_billing_for_email $promotion["billing"];
  2748.                 $with_discount_billing_for_PhoneNumber $promotion["billing"];
  2749.                 $is_shipping_promo 1;
  2750.                 $haveBillingDiscount true;
  2751.             }
  2752.         }
  2753.         foreach ($food_command as $i => $food) {
  2754.             if ($i != 0$food_litteral .= "+";
  2755.             $food_command[$i]["food_entity"] = [];
  2756.             $foods $this->entityManager->getRepository(Food::class)->find($food["food_id"]);
  2757.             $food_litteral .= $foods->getName();
  2758.             if ($foods->getPromotion() == 0) {
  2759.                 $price += intval($foods->getPrice()) * intval($food["quantity"]);
  2760.             } else {
  2761.                 $promotion_price 1;
  2762.                 if ($foods->getPromotionPrice() != null) {
  2763.                     $promotion_price intval($foods->getPromotionPrice());
  2764.                 } else {
  2765.                     $promotion_price intval($foods->getPrice());
  2766.                 }
  2767.                 $price += ($promotion_price intval($food["quantity"]));
  2768.             }
  2769.             $without_promotion_price += (intval($foods->getPrice()) * intval($food["quantity"]));
  2770.             $vouch_price intval($foods->getPrice()) * intval($food["quantity"]);
  2771.             $vouch_price_for_individual_food intval($foods->getPrice());
  2772.             $reduction 0;
  2773.             $owner_gain 0;
  2774.             if (
  2775.                 $check_voucher_valid["valid"] == true ||
  2776.                 sizeof($check_voucher_valid["products"]) == 0
  2777.             ) {
  2778.                 if (
  2779.                     in_array(intval($food["food_id"]), $check_voucher_valid["products"])
  2780.                     || sizeof($check_voucher_valid["products"]) == 0
  2781.                 ) {
  2782.                     if ($check_voucher_valid["type"] == || $check_voucher_valid["type"] == 3) {
  2783.                         if ($check_voucher_valid["category"] == 1) {
  2784.                             $reduction = (intval($foods->getPrice()) * $check_voucher_valid["value"]) / 100;
  2785.                             $is_voucher_used true;
  2786.                             $is_food_voucher_used true;
  2787.                         } else {
  2788.                             $reduction $check_voucher_valid["value"];
  2789.                             $is_voucher_used true;
  2790.                             $is_food_voucher_used true;
  2791.                         }
  2792.                     }
  2793.                     if (($check_voucher_valid["type"] == || $check_voucher_valid["type"] == 3) &&
  2794.                         in_array($restaurant_id$check_voucher_valid["restaurants"])
  2795.                     ) {
  2796.                         if (!$is_voucher_on_billing_already_applyed) {
  2797.                             if ($check_voucher_valid["category"] == 1) {
  2798.                                 $reductions = ($voucher_billing $check_voucher_valid["value"]) / 100;
  2799.                                 $voucher_billing -= $reductions;
  2800.                                 $voucherBillingForPhoneNumber -= $reductions;
  2801.                                 $voucherBillingForEmail -= $reductions;
  2802.                                 $is_voucher_used true;
  2803.                                 $is_billing_voucher_used true;
  2804.                                 $is_voucher_on_billing_already_applyed true;
  2805.                             } else {
  2806.                                 $voucher_billing -= $check_voucher_valid["value"];
  2807.                                 $voucherBillingForPhoneNumber -= $check_voucher_valid["value"];
  2808.                                 $voucherBillingForEmail -= $check_voucher_valid["value"];
  2809.                                 $is_voucher_used true;
  2810.                                 $is_billing_voucher_used true;
  2811.                                 $is_voucher_on_billing_already_applyed true;
  2812.                                 $haveBillingDiscount true;
  2813.                             }
  2814.                         }
  2815.                     }
  2816.                     if ($check_voucher_owners != null) {
  2817.                         if ($check_voucher_valid["voucher"] != null) {
  2818.                             $voucher $check_voucher_valid["voucher"];
  2819.                             if ($voucher["is_rewarded"] == && $voucher["reward_on_food"] == 1) {
  2820.                                 if ($is_billing_voucher_used && ($voucher["reward_type"] == || $voucher["reward_type"] == 3)) {
  2821.                                     $voucher_owner_billing_gain = (intval($billing) * $voucher["reward_percentage_value"]) / 100;
  2822.                                     break;
  2823.                                 }
  2824.                                 if ($is_food_voucher_used && ($voucher["reward_type"] == || $voucher["reward_type"] == 3)) {
  2825.                                     $owner_gain = (intval($vouch_price) * $voucher["reward_percentage_value"]) / 100;
  2826.                                 }
  2827.                             }
  2828.                         }
  2829.                     }
  2830.                 }
  2831.             }
  2832.             if ($reduction >= $vouch_price) {
  2833.                 $final_food_price 0;
  2834.             } else {
  2835.                 $final_food_price $vouch_price - ($reduction intval($food["quantity"]));
  2836.             }
  2837.             if ($reduction >= $vouch_price_for_individual_food) {
  2838.                 $final_food_price_for_individual_food 0;
  2839.             } else {
  2840.                 $final_food_price_for_individual_food $vouch_price_for_individual_food $reduction;
  2841.             }
  2842.             $voucher_food_price += $final_food_price;
  2843.             $voucher_owner_food_price_gain += $owner_gain;
  2844.             $food_command[$i]["food_entity"] = $this->foodApiForMobileToArray($foods);
  2845.             $food_command[$i]["food_entity"]["promotion_voucher"] = 0;
  2846.             if ($is_voucher_used && $is_food_voucher_used) {
  2847.                 $food_command[$i]["food_entity"]["promotion_voucher"] = 1;
  2848.                 $food_command[$i]["food_entity"]["promotion"] = 1;
  2849.                 $food_command[$i]["food_entity"]["promotion_price"] = '' $final_food_price_for_individual_food;
  2850.             }
  2851.             $food_command[$i]["food_shipping"] = [];
  2852.             $food_command[$i]["food_shipping"]["is_shipping_promo"] = $is_shipping_promo;
  2853.             $food_command[$i]["food_shipping"]["shipping_pricing"] = intval($without_promotion_billing);
  2854.             $food_command[$i]["food_shipping"]["phoneNumber_shipping_pricing"] = intval($without_promotion_billing_for_PhoneNumber);
  2855.             $food_command[$i]["food_shipping"]["email_shipping_pricing"] = intval($without_promotion_billing_for_email);
  2856.         }
  2857.         $adress_entity $this->entityManager->getRepository(Adresses::class)->findOneBy(['location' => $address["location"]]);
  2858.         $additional_fees $this->getAdditionalFeesPrice($food_command$price$billing$adress_entity$restaurant);
  2859.         $additional_fee_total_price $this->getAdditionalFeesTotalPricing($additional_fees);
  2860.         $food_price $price;
  2861.         $food_billing $billing;
  2862.         $data = [];
  2863.         $preorder_config =  $this->entityManager->getRepository(PreOrderConfig::class)->findBy(
  2864.             array(),
  2865.             array('id' => 'DESC'),
  2866.             1,
  2867.             0
  2868.         );
  2869.         $discount 0;
  2870.         if ($preorder_config != null) {
  2871.             $config $preorder_config[0];
  2872.             $discount $config->getReduction();
  2873.         }
  2874.         $with_discount = ((100 $discount) * $without_promotion_billing 100);
  2875.         $preorderBillingForPhoneNumber = ((100 $discount) * $without_promotion_billing_for_PhoneNumber 100);
  2876.         $preorderBillingForEmail = ((100 $discount) * $without_promotion_billing_for_email 100);
  2877.         $data["without_promo"]["pre_order"]["total"] = $with_discount $without_promotion_price $additional_fee_total_price;
  2878.         $data["without_promo"]["pre_order"]["billing"] = $with_discount;
  2879.         if ($preorder == 1) {
  2880.             $food_price $without_promotion_price;
  2881.             $food_billing $with_discount;
  2882.             $with_discount_billing_for_email $preorderBillingForEmail;
  2883.             $with_discount_billing_for_PhoneNumber $preorderBillingForPhoneNumber;
  2884.             $haveBillingDiscount true;
  2885.         }
  2886.         $voucher_food_price intval($voucher_food_price) < $voucher_food_price;
  2887.         $voucher_billing intval($voucher_billing) < $voucher_billing;
  2888.         if ($is_billing_voucher_used) {
  2889.             $food_billing $voucher_billing;
  2890.             $with_discount_billing_for_email $voucherBillingForEmail;
  2891.             $with_discount_billing_for_PhoneNumber $voucherBillingForPhoneNumber;
  2892.             $haveBillingDiscount true;
  2893.         }
  2894.         if ($is_food_voucher_used) {
  2895.             $food_price $voucher_food_price;
  2896.         }
  2897.         $is_kaba_point_used false;
  2898.         $kaba_point_used_amount 0;
  2899.         if ($use_kaba_point) {
  2900.             $kabaPoint $this->getMiniKabaPointBalance($user_id$without_promotion_billing);
  2901.             $data["kaba_point"] = $kabaPoint;
  2902.             $amount intval($kabaPoint["amount_to_reduce"]);
  2903.             if ($kabaPoint['can_be_used']) {
  2904.                 $haveBillingDiscount true;
  2905.                 $is_kaba_point_used true;
  2906.                 if ($amount >= $without_promotion_billing) {
  2907.                     $billing 0;
  2908.                     $food_billing $billing;
  2909.                     $kaba_point_used_amount $without_promotion_billing;
  2910.                     $with_discount_billing_for_email $amount >= $without_promotion_billing_for_email $without_promotion_billing_for_email $amount;
  2911.                     $with_discount_billing_for_PhoneNumber $amount >= $without_promotion_billing_for_PhoneNumber $without_promotion_billing_for_PhoneNumber $amount;
  2912.                 } else {
  2913.                     $kaba_point_used_amount $amount;
  2914.                     $billing $without_promotion_billing $amount;
  2915.                     $food_billing $billing;
  2916.                     $with_discount_billing_for_email $without_promotion_billing_for_email $amount;
  2917.                     $with_discount_billing_for_PhoneNumber $without_promotion_billing_for_PhoneNumber $amount;
  2918.                 }
  2919.             } else {
  2920.                 $data["kaba_point"] = $kabaPoint;
  2921.             }
  2922.         } else {
  2923.             $data["kaba_point"] = $kabaPoint;
  2924.         }
  2925.         $data["voucher_pricing"] = [];
  2926.         $data["voucher_pricing"]["valid"] = $check_voucher_valid["valid"];
  2927.         $data["voucher_pricing"]["command_pricing"] = intval($voucher_food_price);
  2928.         $data["voucher_pricing"]["shipping_pricing"] = intval($voucher_billing);
  2929.         $data["voucher_pricing"]["total_pricing"] = intval($voucher_food_price $voucher_billing $additional_fee_total_price);
  2930.         $data["voucher_pricing"]["owner"] = [];
  2931.         if ($voucher_id == null) {
  2932.             $data["voucher_pricing"]["owner"]["is_rewarded"] = null;
  2933.             $data["voucher_pricing"]["owner"]["reward_on_food"] = null;
  2934.             $data["voucher_pricing"]["owner"]["reward_cash_value"] = null;
  2935.             $data["voucher_pricing"]["owner"]["reward_type"] = null;
  2936.         } else {
  2937.             $data["voucher_pricing"]["owner"]["is_rewarded"] = $check_voucher_valid["voucher"]["is_rewarded"];
  2938.             $data["voucher_pricing"]["owner"]["reward_on_food"] = $check_voucher_valid["voucher"]["reward_on_food"];
  2939.             $data["voucher_pricing"]["owner"]["reward_cash_value"] = $check_voucher_valid["voucher"]["reward_cash_value"];
  2940.             $data["voucher_pricing"]["owner"]["reward_type"] = $check_voucher_valid["voucher"]["reward_type"];
  2941.         }
  2942.         $data["voucher_pricing"]["owner"]["reward_on_billing"] = intval($voucher_owner_billing_gain);
  2943.         $data["voucher_pricing"]["owner"]["reward_on_food"] = intval($voucher_owner_food_price_gain);
  2944.         $data["is_voucher_used"] = $is_voucher_used;
  2945.         $data["is_food_voucher_used"] = $is_food_voucher_used;
  2946.         $data["is_billing_voucher_used"] = $is_billing_voucher_used;
  2947.         $data["discount"] = $discount;
  2948.         $data["is_kaba_point_used"] = $is_kaba_point_used;
  2949.         $data["kaba_point_used_amount"] = $kaba_point_used_amount;
  2950.         $data["foods"] = $food_command;
  2951.         $data["food_litteral"] = $food_litteral;
  2952.         $data["food_price"] = $food_price;
  2953.         $data["food_billing"] = $food_billing;
  2954.         $data["food_total"] = $food_price $food_billing;
  2955.         $data["with_promo"]["price"] = $price $additional_fee_total_price;
  2956.         $data["with_promo"]["billing"] = $billing;
  2957.         $data["with_promo"]["total"] = $billing $price $additional_fee_total_price;
  2958.         $data["without_promo"]["price"] = intval($without_promotion_price $additional_fee_total_price);
  2959.         $data["without_promo"]["billing"] = intval($without_promotion_billing);
  2960.         $data["without_promo"]["total"] = intval($without_promotion_billing $without_promotion_price $additional_fee_total_price);
  2961.         $data["phoneNumber_shipping_pricing"] = intval($with_discount_billing_for_PhoneNumber);
  2962.         $data["email_shipping_pricing"] = intval($with_discount_billing_for_email);
  2963.         $data["base_shipping_pricing"] = intval($standard_price["billing"]);
  2964.         $data["extra_shipping_pricing"] = $extra_shipping_pricing $extra_shipping_pricing 0;
  2965.         $data["haveBillingDiscount"] = $haveBillingDiscount;
  2966.         return $data;
  2967.     }
  2968.     public function foodApiForMobileToArray($food)
  2969.     {
  2970.         $res = [];
  2971.         $res["id"] = $food->getId();
  2972.         $res["name"] = $food->getName();
  2973.         $res["description"] = $food->getDescription();
  2974.         $res["promotion"] = $this->checkFoodPromoState($food)["promo"];
  2975.         $res["promotion_price"] = $food->getPromotionPrice() == null "0" $food->getPromotionPrice();
  2976.         $res["pic"] = $this->getParameter('fp') . '/' $food->getPic();
  2977.         if ($food->getFoodDetailsPictures() != null && sizeof($food->getFoodDetailsPictures()) > 0) {
  2978.             $i 0;
  2979.             foreach ($food->getFoodDetailsPictures() as $food_pic) {
  2980.                 $res["food_details_pictures"][$i] = $this->getParameter('fp') . '/' $food_pic;
  2981.                 $i++;
  2982.             }
  2983.         }
  2984.         $res["price"] = $food->getPrice();
  2985.         $res["menu_id"] = $food->getMenuId();
  2986.         $lastUpdate $food->getLastUpdate();
  2987.         if ($lastUpdate instanceof \DateTimeInterface) {
  2988.             $res["lastupdate"] = $lastUpdate->format(DATE_ATOM);
  2989.         } elseif (is_string($lastUpdate) && strtotime($lastUpdate) !== false) {
  2990.             $res["lastupdate"] = date(DATE_ATOMstrtotime($lastUpdate));
  2991.         } else {
  2992.             $res["lastupdate"] = null;
  2993.         }
  2994.         return $res;
  2995.     }
  2996.     private function isFirstCommandBonusApply($id)
  2997.     {
  2998.         $loyalty $this->entityManager->getRepository(Loyalty::class)->findOneBy([
  2999.             "status" => "1"
  3000.         ]);
  3001.         $today = new \DateTime();
  3002.         $countUserCommand count($this->entityManager->getRepository(Command::class)->findBy([
  3003.             'clientId' => $id,
  3004.             'state' => '3'
  3005.         ]));
  3006.         $haveAlredyBonus =  $this->entityManager->getRepository(PayBonus::class)->findOneBy([
  3007.             'clientId' => $id
  3008.         ]);
  3009.         if (
  3010.             $haveAlredyBonus == null &&
  3011.             $loyalty != null &&
  3012.             $today >= $loyalty->getStartDate() &&
  3013.             $today <= $loyalty->getEndDate() &&
  3014.             $countUserCommand intval($loyalty->getRequired())
  3015.         ) {
  3016.             return ['response' => true'type' => $loyalty->getType()];
  3017.         }
  3018.         return ['response' => false'type' => '-1'];
  3019.     }
  3020.     private function restaurantAcceptPayAtArrival($restaurantId)
  3021.     {
  3022.         $restaurant $this->entityManager->getRepository(RestaurantConfig::class)->find($restaurantId);
  3023.         return $restaurant->getPayAtDelivery();
  3024.     }
  3025.     private function applyFirstCommandProccess($id$commandId$foodPring$shippingPrincing)
  3026.     {
  3027.         $loyalty $this->entityManager->getRepository(Loyalty::class)->findOneBy([
  3028.             "status" => "1"
  3029.         ]);
  3030.         $user =  $this->entityManager->getRepository(Client::class)->find($id);
  3031.         $today = new \DateTime();
  3032.         $userCreatedAt $user->getCreatedAt();
  3033.         $bonus = new PayBonus();
  3034.         $bonus->setCreatedAt($today)
  3035.             ->setClientId($id)
  3036.             ->setCommandDate($today)
  3037.             ->setPayDate($today)
  3038.             ->setPhone($user->getUsername())
  3039.             ->setAccountDate($user->getCreatedAt() ? new \DateTime("@$userCreatedAt") : $today)
  3040.             ->setCommandId($commandId)
  3041.             ->setOfferType($loyalty->getType())
  3042.             ->setStatus('-1')
  3043.             ->setFoodPrice($foodPring)
  3044.             ->setShippingPrice($shippingPrincing)
  3045.             ->setAmount($loyalty->getType() == '1' $shippingPrincing $loyalty->getAmount());
  3046.         $em $this->entityManager;
  3047.         $em->persist($bonus);
  3048.         $em->flush();
  3049.     }
  3050.     private function restaurantAcceptPrepay($restaurantId)
  3051.     {
  3052.         $restaurant $this->entityManager->getRepository(RestaurantConfig::class)->find($restaurantId);
  3053.         return $restaurant->getPrepayed();
  3054.     }
  3055.     private function restaurantAcceptPreOrder($restaurantId$timeRange/*plage*/)
  3056.     {
  3057.         $preorder_config $this->entityManager->getRepository(PreOrderConfig::class)->findBy(
  3058.             array(),
  3059.             array('id' => 'DESC'),
  3060.             1,
  3061.             0
  3062.         );
  3063.         if ($preorder_config != null) {
  3064.             $config $preorder_config[0];
  3065.             $delay 3600 * (intval($config->getDelay()));
  3066.             $max_hour_range intval($config->getMaxHour());
  3067.             $restaurant $this->entityManager->getRepository(RestaurantConfig::class)->find($restaurantId);
  3068.             $data $this->getPreorderDatas($restaurant->getPreorderScheduleId(), $delay$max_hour_range);
  3069.             if ($data["can_preorder"] == && in_array($timeRange$data["hours"])) {
  3070.                 return true;
  3071.             }
  3072.             return false;
  3073.         } else {
  3074.             return false;
  3075.         }
  3076.     }
  3077.     private function get_kaba_point($client_id$shipping_price)
  3078.     {
  3079.         $kabaPoint $this->getMiniKabaPointBalance($client_id$shipping_price);
  3080.         return $kabaPoint;
  3081.     }
  3082.     private function getAdditionalFeesPrice($food_command$command_pricing$shipping_price$address$restaurant)
  3083.     {
  3084.         $commission_fee 0;
  3085.         $packaging_fee 0;
  3086.         $weather_fee 0;
  3087.         $night_fee 0;
  3088.         $week_end_fee 0;
  3089.         $holy_day_fee 0;
  3090.         //ADD COMMISSION FEE
  3091.         $additional_fee $this->entityManager->getRepository(AdditionalFees::class)->findOneBy(["fee_type" => AdditionnalFeeType::COMMISSION_FEE]);
  3092.         $commission_additional_fee $this->entityManager->getRepository(RestoFraisSupp::class)->findOneBy(["resto_id" => $restaurant->getId(), "additional_fee_id" => $additional_fee->getId()]);
  3093.         if($commission_additional_fee == null){
  3094.             $isEnabled false;
  3095.         }else{
  3096.             $isEnabled =  $commission_additional_fee->isFeeEnabled();
  3097.         }
  3098.         if ($isEnabled == true) {
  3099.             if ($commission_additional_fee->getAmountType() == AdditionnalFeeAmountType::PRIX_FIX) {
  3100.                 $commission_fee $commission_additional_fee->getValue();
  3101.             } else {
  3102.                 $commission_fee = ($command_pricing  * ($commission_additional_fee->getValue() / 100));
  3103.             }
  3104.         }
  3105.         //ADD PACKAGING_FEE
  3106.         $additional_fee $this->entityManager->getRepository(AdditionalFees::class)->findOneBy(["fee_type" => AdditionnalFeeType::PACKAGING_FEE]);
  3107.         $packaging_additional_fee $this->entityManager
  3108.             ->getRepository(RestoFraisSupp::class)
  3109.             ->findOneBy([
  3110.                 "resto_id" => $restaurant->getId(),
  3111.                 "additional_fee_id" => $additional_fee->getId()
  3112.             ]);
  3113.         if($packaging_additional_fee == null){
  3114.             $isEnabled false;
  3115.         }else{
  3116.             $isEnabled $packaging_additional_fee->isFeeEnabled();
  3117.         }
  3118.         
  3119.         if ($isEnabled == true) {
  3120.             $billing 0;
  3121.             $db_billing =  $this->entityManager->getRepository(PackagingAdditionnalFeeBilling::class)->findAll();
  3122.             $number_of_products 0;
  3123.             foreach ($food_command as $food) {
  3124.                 $number_of_products += $food['quantity'];
  3125.             }
  3126.             if ($db_billing != null) {
  3127.                 foreach ($db_billing as $db_billing_item) {
  3128.                     if ($number_of_products >= intval($db_billing_item->getRangeStart())  && $number_of_products <= intval($db_billing_item->getRangeEnd())) {
  3129.                         $billing $db_billing_item->getValue();
  3130.                     }
  3131.                 }
  3132.             }
  3133.             $packaging_fee intval($billing);
  3134.         }
  3135.         try{
  3136.         //ADD WEATHER_FEE 
  3137.         $raining_in_resto_zone false;
  3138.         $raining_in_customer_zone false;
  3139.         //check if order's zone
  3140.         $order_zone $this->entityManager->getRepository(ZoneResto::class)->findOneBy(['resto_id' => $restaurant->getId()]);
  3141.         if ($order_zone) {
  3142.             $weather_rule $this->entityManager->getRepository(WeatherRule::class)->findOneBy(['zone_id' => $order_zone->getZoneId()]);
  3143.             if ($weather_rule) {
  3144.                 $current_time = new DateTime();
  3145.                 $time_end $weather_rule->getTimeEnd();
  3146.                 $time_start $weather_rule->getTimeStart();
  3147.                 if ($current_time->format('H:i') >= $time_start->format('H:i') && $current_time->format('H:i') <= $time_end->format('H:i'))
  3148.                     $raining_in_resto_zone $weather_rule->isEnabled();
  3149.                 if ($current_time->format('H:i') > $time_end->format('H:i')) {
  3150.                     $raining_in_resto_zone false;
  3151.                     $weather_rule->setEnabled(false);
  3152.                     $this->entityManager->persist($weather_rule);
  3153.                     $this->entityManager->flush();
  3154.                 }
  3155.             }
  3156.         }
  3157.         //check shipping zone 
  3158.         $zones =  $this->entityManager->getRepository(Zone::class)->findAll();
  3159.         $customer_zone null;
  3160.         foreach ($zones as $zone) {
  3161.             list($clientLat$clientLng) = explode(':'$address->getLocation());
  3162.             $location json_decode($zone->getLocation(), true);
  3163.             $latitude $location['lat'];
  3164.             $longitude $location['lng'];
  3165.             $distance $this->haversineDistance(
  3166.                 (float)$clientLat,
  3167.                 (float)$clientLng,
  3168.                 $latitude,
  3169.                 $longitude
  3170.             );
  3171.             if ($distance <= $zone->getRadius()) {
  3172.                 $customer_zone $zone;
  3173.                 break;
  3174.             }
  3175.         }
  3176.         if ($customer_zone) {
  3177.             $weatherRuleForClientZone $this->entityManager->getRepository(WeatherRule::class)->findOneBy(['zone_id' => $customer_zone->getId()]);
  3178.             $raining_in_customer_zone $weatherRuleForClientZone->isEnabled();
  3179.             if ($raining_in_customer_zone == true || $raining_in_resto_zone == true) {
  3180.                 $weather_additional_fee $this->entityManager->getRepository(AdditionalFees::class)->findByFeeType(AdditionnalFeeType::WEATHER_FEE);
  3181.                 if ($weather_additional_fee->getAmountType() == AdditionnalFeeAmountType::PRIX_FIX) {
  3182.                     $weather_fee $weather_additional_fee->getAmountValue();
  3183.                 } else {
  3184.                     $weather_fee = ($shipping_price  * ($weather_additional_fee->getAmountValue() / 100));
  3185.                 }
  3186.             }
  3187.         } else
  3188.             $weather_fee 0;
  3189.         }catch(Throwable $e){
  3190.             $weather_fee=0;
  3191.         }
  3192.         //ADD NIGHT_FEE 
  3193.         $current_time = new DateTime();
  3194.         $night_additional_fee $this->entityManager->getRepository(AdditionalFees::class)->findByFeeType(AdditionnalFeeType::NIGHT_FEE);
  3195.         $night_rule $this->entityManager->getRepository(AdditionalFeeRule::class)->findOneby(['rule_type' => AdditionalFeeRuleType::TIME_FRAME]);
  3196.         $night_time_start $night_rule->getTimeStart();
  3197.         $night_time_end $night_rule->getTimeEnd();
  3198.         if ($current_time->format('H:i') >= $night_time_start->format('H:i') && $current_time->format('H:i') < $night_time_end->format('H:i')) {
  3199.             if ($night_additional_fee->isEnabled()) {
  3200.                 if ($night_additional_fee->getAmountType() == AdditionnalFeeAmountType::PRIX_FIX) {
  3201.                     $night_fee $night_additional_fee->getAmountValue();
  3202.                 } else {
  3203.                     $night_fee = ($shipping_price  * ($night_additional_fee->getAmountValue() / 100));
  3204.                 }
  3205.             }
  3206.         }
  3207.         //ADD WEEK_END FEE and HOLYDAY FEE
  3208.         $week_end_additional_fee $this->entityManager->getRepository(AdditionalFees::class)->findByFeeType(AdditionnalFeeType::NIGHT_FEE);
  3209.         $public_holyday_additional_fee $this->entityManager->getRepository(AdditionalFees::class)->findByFeeType(AdditionnalFeeType::PUBLIC_HOLYDAY_FEE);
  3210.         $free_day_rule $this->entityManager->getRepository(AdditionalFeeRule::class)->findOneby(['rule_type' => AdditionalFeeRuleType::FREE_DAY_FRAME]);
  3211.         $free_day_time_start $free_day_rule->getTimeStart();
  3212.         $free_day_time_end $free_day_rule->getTimeEnd();
  3213.         if ($current_time->format('H:i') >= $free_day_time_start->format('H:i') && $current_time->format('H:i') < $free_day_time_end->format('H:i')) {
  3214.             if ($week_end_additional_fee->isEnabled() && ($current_time->format('N') == || $current_time->format('N') == 7)) {
  3215.                 if ($week_end_additional_fee->getAmountType() == AdditionnalFeeAmountType::PRIX_FIX) {
  3216.                     $week_end_fee $week_end_additional_fee->getAmountValue();
  3217.                 } else {
  3218.                     $week_end_fee = ($shipping_price  * ($week_end_additional_fee->getAmountValue() / 100));
  3219.                 }
  3220.             }
  3221.             if ($public_holyday_additional_fee->isEnabled()) {
  3222.                 if ($public_holyday_additional_fee->getAmountType() == AdditionnalFeeAmountType::PRIX_FIX) {
  3223.                     $holy_day_fee $public_holyday_additional_fee->getAmountValue();
  3224.                 } else {
  3225.                     $holy_day_fee = ($shipping_price  * ($public_holyday_additional_fee->getAmountValue() / 100));
  3226.                 }
  3227.             }
  3228.         }
  3229.         $fees = [$weather_fee$night_fee$week_end_fee$holy_day_fee];
  3230.         $count 0;
  3231.         foreach ($fees as $fee) {
  3232.             if ($fee 0) {
  3233.                 $count++;
  3234.             }
  3235.         }
  3236.         if ($count 2) {
  3237.             $weather_additional_fee $this->entityManager->getRepository(AdditionalFees::class)->findOneBy(["fee_type" => AdditionnalFeeType::WEATHER_FEE]);
  3238.             $night_additional_fee $this->entityManager->getRepository(AdditionalFees::class)->findOneBy(["fee_type" => AdditionnalFeeType::NIGHT_FEE]);
  3239.             $week_end_additional_fee $this->entityManager->getRepository(AdditionalFees::class)->findOneBy(["fee_type" => AdditionnalFeeType::WEEKEND_FEE]);
  3240.             $public_holiday_additional_fee $this->entityManager->getRepository(AdditionalFees::class)->findOneBy(["fee_type" => AdditionnalFeeType::PUBLIC_HOLYDAY_FEE]);
  3241.             $fees_entities = [$weather_additional_fee$night_additional_fee$week_end_additional_fee$public_holiday_additional_fee];
  3242.             usort($fees_entities, function ($a$b) {
  3243.                 return $a->getPriority() - $b->getPriority();
  3244.             });
  3245.             $top_two_entities array_slice($fees_entities02);
  3246.             $selected_fee_types = [];
  3247.             foreach ($top_two_entities as $entity) {
  3248.                 $selected_fee_types[] = $entity->getFeeType();
  3249.             }
  3250.             if (!in_array(AdditionnalFeeType::WEATHER_FEE$selected_fee_types)) {
  3251.                 $weather_fee 0;
  3252.             }
  3253.             if (!in_array(AdditionnalFeeType::NIGHT_FEE$selected_fee_types)) {
  3254.                 $night_fee 0;
  3255.             }
  3256.             if (!in_array(AdditionnalFeeType::WEEKEND_FEE$selected_fee_types)) {
  3257.                 $week_end_fee 0;
  3258.             }
  3259.             if (!in_array(AdditionnalFeeType::PUBLIC_HOLYDAY_FEE$selected_fee_types)) {
  3260.                 $holy_day_fee 0;
  3261.             }
  3262.         }
  3263.         $res = [];
  3264.         $res["COMMISSION_FEE"] = $commission_fee;
  3265.         $res["PACKAGING_FEE"] = $packaging_fee;
  3266.         $res["WEATHER_FEE"] = $weather_fee;
  3267.         $res["NIGHT_FEE"] = $night_fee;
  3268.         $res["PUBLIC_HOLYDAY_FEE"] = $holy_day_fee;
  3269.         $res["WEEKEND_FEE"] = $week_end_fee;
  3270.         return $res;
  3271.     }
  3272.     private function getPromotionPricing($data$configs_with_voucher)
  3273.     {
  3274.         $promotionPricing 0;
  3275.         foreach ($data["food_command"] as $json_food_command) {
  3276.             $food $this->entityManager->getRepository(Food::class)->find(intval($json_food_command["food_id"]));
  3277.             $check_food_promo $this->checkFoodPromoState($food);
  3278.             if ($check_food_promo["promo"] == 1)
  3279.                 $promotionPricing += intval($food->getPromotionPrice()) * intval($json_food_command["quantity"]);
  3280.             else
  3281.                 $promotionPricing += intval($food->getPrice()) * intval($json_food_command["quantity"]);
  3282.         }
  3283.         if (isset($data["voucher_id"]) && $data["voucher_id"] != null) {
  3284.             $voucher_food_price intval($configs_with_voucher["voucher_food_price"]) < $configs_with_voucher["voucher_food_price"];
  3285.             $promotionPricing intval($voucher_food_price);
  3286.         }
  3287.         return $promotionPricing;
  3288.     }
  3289.     public function checkFoodPromoState($food)
  3290.     {
  3291.         $data = [];
  3292.         $foods["schedule"] = [];
  3293.         if ($food->getId() != null) {
  3294.             $sched $this->entityManager->getRepository(PromotionSchedule::class)->findOneBy([
  3295.                 'foodId' => $food->getId()
  3296.             ]);
  3297.             if ($sched != null) {
  3298.                 $foods["schedule"] = $this->promotionScheduleToArray($sched);
  3299.             }
  3300.         }
  3301.         if (isset($foods["schedule"]) && $foods["schedule"] != null && isset($foods["schedule"]["content_details"]) && $foods["schedule"]["content_details"] != null) {
  3302.             $schedule $foods["schedule"];
  3303.             /*get day in format ==>exp: 'Monday'  and the day_index in the week==>exp: 1 (first day of week)*/
  3304.             $day_of_week $this->getDayOfWeek(date("Y-m-d"));
  3305.             foreach ($schedule["content_details"] as $detail) {
  3306.                 /*we find today date schedule program*/
  3307.                 if ($detail["day_index"] == $day_of_week["day_index"]) {
  3308.                     if ($detail["promo"] == 0) {
  3309.                         $data["promo"] = 0;
  3310.                         return $data;
  3311.                     } else {
  3312.                         $promo 0;
  3313.                         $now strtotime(date('H:i'));
  3314.                         /*if start <now< end*/
  3315.                         if (($detail["start"] != '' && $detail["end"] != '') || ($detail["start"] != null && $detail["end"] != null)) {
  3316.                             if ($now >= strtotime($detail["start"]) && $now strtotime($detail["end"])) {
  3317.                                 $promo 1;
  3318.                             }
  3319.                             if (
  3320.                                 strtotime('00:00') <= strtotime($detail["end"]) &&
  3321.                                 strtotime($detail["end"]) < strtotime($detail["start"])
  3322.                             ) {
  3323.                                 /*if*/
  3324.                                 if ($now strtotime($detail["end"]) || $now >= strtotime($detail["start"])) {
  3325.                                     $promo 1;
  3326.                                 }
  3327.                             }
  3328.                         }
  3329.                         $data["promo"] = $promo;
  3330.                         return $data;
  3331.                     }
  3332.                 }
  3333.             }
  3334.         } else {
  3335.             $data["promo"] = $food->getPromotion();
  3336.             return $data;
  3337.         }
  3338.     }
  3339.     private function get_total_pricing($res$configs_with_voucher$data$client_id$kabaPoint)
  3340.     {
  3341.         $total_normal_pricing 0;
  3342.         if ($res["command_pricing"] > $res["promotion_pricing"]) {
  3343.             if ($res["shipping_pricing"] > $res["promotion_shipping_pricing"])
  3344.                 $total_normal_pricing $res["promotion_pricing"] + $res["promotion_shipping_pricing"];
  3345.             else
  3346.                 $total_normal_pricing $res["promotion_pricing"] + $res["shipping_pricing"];
  3347.         } else {
  3348.             if ($res["shipping_pricing"] > $res["promotion_shipping_pricing"])
  3349.                 $total_normal_pricing $res["command_pricing"] + $res["promotion_shipping_pricing"];
  3350.             else
  3351.                 $total_normal_pricing $res["command_pricing"] + $res["shipping_pricing"];
  3352.         }
  3353.         if (isset($data["voucher_id"]) && $data["voucher_id"] != null) {
  3354.             $voucher_food_price intval($configs_with_voucher['voucher_food_price']) < $configs_with_voucher["voucher_food_price"];
  3355.             $voucher_billing intval($configs_with_voucher["voucher_billing"]) < $configs_with_voucher["voucher_billing"];
  3356.             $total_normal_pricing intval($voucher_food_price $voucher_billing);
  3357.         }
  3358.         if (isset($data['use_kaba_point']) && $data['use_kaba_point']) {
  3359.             $amount intval($kabaPoint["amount_to_reduce"]);
  3360.             if ($amount >= $res["shipping_pricing"])
  3361.                 $total_normal_pricing $res["promotion_pricing"] + $res["promotion_shipping_pricing"];
  3362.             else
  3363.                 $total_normal_pricing $res["promotion_pricing"] + $res["promotion_shipping_pricing"];
  3364.         }
  3365.         $type = [];
  3366.         $type["total_pricing"] = $total_normal_pricing;
  3367.         $total_normal_pricing $this->price_based_on_loyalty($client_id$type$res["promotion_pricing"], nullnull);
  3368.         $total_normal_pricing += $res['additional_fees_total_price'];
  3369.         return $total_normal_pricing;
  3370.     }
  3371.     private function get_remise($client_id$res$data$kabaPoint)
  3372.     {
  3373.         $remise 0;
  3374.         $total_pricing $res['total_pricing'];
  3375.         $total_without_remise intval($res["command_pricing"]) + intval($res["shipping_pricing"]) + $res['additional_fees_total_price'];
  3376.         $total_with_remise intval($res["promotion_pricing"]) + intval($res["promotion_shipping_pricing"]) + $res['additional_fees_total_price'];
  3377.         $remise '' . (100 $this->getRemise($total_without_remise$total_with_remise));
  3378.         if (isset($data["voucher_id"]) && $data["voucher_id"] != null) {
  3379.             $total_with_voucher_remise intval($res["total_pricing"]);
  3380.             $remise '' . (100 $this->getRemise($total_without_remise$total_with_voucher_remise));
  3381.         }
  3382.         if (isset($data['use_kaba_point']) && $data['use_kaba_point']) {
  3383.             $amount intval($kabaPoint["amount_to_reduce"]);
  3384.             if ($amount >= $res["shipping_pricing"]) {
  3385.                 $total_pricing $res["promotion_pricing"];
  3386.                 $remise  '' . (100 $this->getRemise($total_without_remise$total_pricing));
  3387.             } else {
  3388.                 $promotion_shipping_pricing $res["shipping_pricing"] - $amount;
  3389.                 $total_pricing $res["promotion_pricing"] + $promotion_shipping_pricing;
  3390.                 $remise  '' . (100 $this->getRemise($total_without_remise$total_pricing));
  3391.             }
  3392.         }
  3393.         $type = [];
  3394.         $type['remise'] = $remise;
  3395.         $remise $this->price_based_on_loyalty($client_id$typenull$total_without_remise$total_pricing);
  3396.         return $remise "";
  3397.     }
  3398.     private function isOutOfRange($distance)
  3399.     {
  3400.         if ($distance >= 15000)
  3401.             return true;
  3402.         else
  3403.             return false;
  3404.     }
  3405.     private function calculate_command_pricing($foods)
  3406.     {
  3407.         $products_total_price 0;
  3408.         foreach ($foods as $json_food_command) {
  3409.             $food $this->entityManager->getRepository(Food::class)->find(intval($json_food_command["food_id"]));
  3410.             $products_total_price += intval($food->getPrice()) * intval($json_food_command["quantity"]);
  3411.         }
  3412.         return $products_total_price;
  3413.     }
  3414.     private function calculate_shipping_price($distance$currentToken)
  3415.     {
  3416.         $type filter_var($currentToken->getUsername(), FILTER_VALIDATE_EMAIL) ? 1;
  3417.         $shipping_price 0;
  3418.         $billing 0;
  3419.         $db_billing $type == ?  $this->entityManager->getRepository(Billing2::class)->findAll() :  $this->entityManager->getRepository(Billing::class)->findAll();
  3420.         if ($db_billing != null) {
  3421.             foreach ($db_billing as $db_billing_item) {
  3422.                 if ($distance >= intval($db_billing_item->getRangeStart()) * 1000 && $distance intval($db_billing_item->getRangeEnd()) * 1000) {
  3423.                     $billing $db_billing_item->getValue();
  3424.                 }
  3425.             }
  3426.         }
  3427.         $shipping_price intval($billing);
  3428.         if ($shipping_price == 0) {
  3429.             return $this->serializer->serialize($distance"json");
  3430.         }
  3431.         return $shipping_price;
  3432.     }
  3433.     private function configsWithVoucher($data$currentToken$user$restaurant$address)
  3434.     {
  3435.         $distance $this->getDistance($restaurant->getLocation(), $address->getLocation());
  3436.         $promotion_billing 0;
  3437.         $voucher_billing 0;
  3438.         $voucher_food_price 0;
  3439.         $is_voucher_on_billing false;
  3440.         $is_voucher_on_billing_already_applyed false;
  3441.  
  3442.         $check_voucher_valid $this->checkIfVoucherValid($user->getId(), $data["voucher_id"]);
  3443.         $promotion $this->checkEligiblePromotionV2($distance"" $restaurant->getId(), $data["food_command"], $user);
  3444.         $type filter_var($currentToken->getUsername(), FILTER_VALIDATE_EMAIL) ? 1;
  3445.         $db_billing $type == ?  $this->entityManager->getRepository(Billing2::class)->findAll() :  $this->entityManager->getRepository(Billing::class)->findAll();
  3446.         if ($db_billing != null) {
  3447.             foreach ($db_billing as $db_billing_item) {
  3448.                 if (
  3449.                     $distance >= intval($db_billing_item->getRangeStart()) * 1000 &&
  3450.                     $distance intval($db_billing_item->getRangeEnd()) * 1000
  3451.                 ) {
  3452.                     $billing $db_billing_item->getValue();
  3453.                     $voucher_billing intval($billing);
  3454.                     if ($check_voucher_valid["valid"] == true) {
  3455.                         /*check if restaurant is in array of concern restaurants*/
  3456.                         if (in_array($data["restaurant_id"], $check_voucher_valid["restaurants"])) {
  3457.                             $is_voucher_on_billing true;
  3458.                             break;
  3459.                         }
  3460.                     }
  3461.                     if ($promotion["found"] == true) {
  3462.                         $promotion_billing $promotion["billing"];
  3463.                     } else
  3464.                         $promotion_billing $billing;
  3465.                 }
  3466.             }
  3467.         }
  3468.         foreach ($data["food_command"] as $json_food_command) {
  3469.             $food $this->entityManager->getRepository(Food::class)->find(intval($json_food_command["food_id"]));
  3470.             $vouch_price intval($food->getPrice()) * intval($json_food_command["quantity"]);
  3471.             $reduction 0;
  3472.             if ($check_voucher_valid["valid"] == true) {
  3473.                 if ($check_voucher_valid["isAllRestaurant"] && $check_voucher_valid["isAllFood"]) {
  3474.                     /* check if reduction on food or both food and billing*/
  3475.                     if ($check_voucher_valid["type"] == || $check_voucher_valid["type"] == 3) {
  3476.                         if ($check_voucher_valid["category"] == 1) {
  3477.                             /*in percent*/
  3478.                             $reduction = (intval($food->getPrice()) * $check_voucher_valid["value"]) / 100;
  3479.                         } else {
  3480.                             $reduction $check_voucher_valid["value"];
  3481.                         }
  3482.                     }
  3483.                     /* check if reduction on billing or both billing and food*/
  3484.                     if ($check_voucher_valid["type"] == || $check_voucher_valid["type"] == 3) {
  3485.                         /*check if restaurant is in array of concern restaurants means==>is_voucher_billing=true*/
  3486.                         if ($is_voucher_on_billing && !$is_voucher_on_billing_already_applyed) {
  3487.                             if ($check_voucher_valid["category"] == 1) {
  3488.                                 /*in percent*/
  3489.                                 $reductions = ($voucher_billing $check_voucher_valid["value"]) / 100;
  3490.                                 $voucher_billing -= $reductions;
  3491.                                 $is_voucher_on_billing_already_applyed true;
  3492.                             } else {
  3493.                                 /*cash*/
  3494.                                 $voucher_billing -= $check_voucher_valid["value"];
  3495.                                 $is_voucher_on_billing_already_applyed true;
  3496.                             }
  3497.                         }
  3498.                     }
  3499.                 } elseif (
  3500.                     in_array(intval($json_food_command["food_id"]), $check_voucher_valid["products"]) ||
  3501.                     sizeof($check_voucher_valid["products"]) == 0
  3502.                 ) {
  3503.                     /*check if that food is in array of concerned foods*/
  3504.                     /*coz if products =[] it means all foods are selected*/
  3505.                     /* check if reduction on food or both food and billing*/
  3506.                     if ($check_voucher_valid["type"] == || $check_voucher_valid["type"] == 3) {
  3507.                         if ($check_voucher_valid["category"] == 1) {
  3508.                             /*in percent*/
  3509.                             $reduction = (intval($food->getPrice()) * $check_voucher_valid["value"]) / 100;
  3510.                         } else {
  3511.                             $reduction $check_voucher_valid["value"];
  3512.                         }
  3513.                     }
  3514.                     /* check if reduction on billing or both billing and food*/
  3515.                     if ($check_voucher_valid["type"] == || $check_voucher_valid["type"] == 3) {
  3516.                         /*check if restaurant is in array of concern restaurants means==>is_voucher_billing=true*/
  3517.                         if ($is_voucher_on_billing && !$is_voucher_on_billing_already_applyed) {
  3518.                             if ($check_voucher_valid["category"] == 1) {
  3519.                                 /*in percent*/
  3520.                                 $reductions = ($voucher_billing $check_voucher_valid["value"]) / 100;
  3521.                                 $voucher_billing -= $reductions;
  3522.                                 $is_voucher_on_billing_already_applyed true;
  3523.                             } else {
  3524.                                 /*cash*/
  3525.                                 $voucher_billing -= $check_voucher_valid["value"];
  3526.                                 $is_voucher_on_billing_already_applyed true;
  3527.                             }
  3528.                         }
  3529.                     }
  3530.                 }
  3531.             }
  3532.             if ($reduction >= $vouch_price) {
  3533.                 $final_food_price 0;
  3534.             } else {
  3535.                 $final_food_price $vouch_price - ($reduction intval($json_food_command["quantity"]));
  3536.             }
  3537.             $voucher_food_price += $final_food_price;
  3538.         }
  3539.         $configs_with_voucher = [];
  3540.         $configs_with_voucher["promotion_billing"] = $promotion_billing;
  3541.         $configs_with_voucher["voucher_billing"] = $voucher_billing;
  3542.         $configs_with_voucher["voucher_food_price"] = $voucher_food_price;
  3543.         $configs_with_voucher["is_voucher_on_billing"] = $is_voucher_on_billing;
  3544.         $configs_with_voucher["is_voucher_on_billing_already_applyed"] = $is_voucher_on_billing_already_applyed;
  3545.         $configs_with_voucher["check_voucher_valid"] = $check_voucher_valid;
  3546.         return $configs_with_voucher;
  3547.     }
  3548.     private function getPromotionOnShipping($restaurant$data$address$currentToken$user$configs_with_voucher$shipping_pricing$kabaPoint)
  3549.     {
  3550.         $distance $this->getDistance($restaurant->getLocation(), $address->getLocation());
  3551.         $promotion_billing 0;
  3552.         $promotion $this->checkEligiblePromotionV2($distance"" $restaurant->getId(), $data["food_command"], $user);
  3553.         $type filter_var($currentToken->getUsername(), FILTER_VALIDATE_EMAIL) ? 1;
  3554.         $db_billing $type == ?  $this->entityManager->getRepository(Billing2::class)->findAll() :  $this->entityManager->getRepository(Billing::class)->findAll();
  3555.         if ($db_billing != null) {
  3556.             foreach ($db_billing as $db_billing_item) {
  3557.                 if (
  3558.                     $distance >= intval($db_billing_item->getRangeStart()) * 1000 &&
  3559.                     $distance intval($db_billing_item->getRangeEnd()) * 1000
  3560.                 ) {
  3561.                     $billing $db_billing_item->getValue();
  3562.                     if ($promotion["found"] == true) {
  3563.                         $promotion_billing $promotion["billing"];
  3564.                     } else
  3565.                         $promotion_billing $billing;
  3566.                 }
  3567.             }
  3568.         }
  3569.         if (isset($data["voucher_id"]) && $data["voucher_id"] != null) {
  3570.             $voucher_billing intval($configs_with_voucher["voucher_billing"]) < $configs_with_voucher["voucher_billing"];
  3571.             $promotion_billing =  intval($voucher_billing);
  3572.         }
  3573.         if (isset($data['use_kaba_point']) && $data['use_kaba_point']) {
  3574.             $amount intval($kabaPoint["amount_to_reduce"]);
  3575.             if ($amount >= $shipping_pricing)
  3576.                 $promotion_billing 0;
  3577.             else
  3578.                 $promotion_billing $shipping_pricing $amount;
  3579.         }
  3580.         $type = [];
  3581.         $type["promotion_shipping_pricing"] = $promotion_billing;
  3582.         $promotion_billing $this->price_based_on_loyalty($user->getId(), $typenullnullnull);
  3583.         return intval($promotion_billing);
  3584.     }
  3585.     private function price_based_on_loyalty($client_id$data$promotion_pricing null$total_without_remise null$total_pricing null)
  3586.     {
  3587.         $price_on_loyalty 0;
  3588.         if (isset($data["promotion_shipping_pricing"]))
  3589.             $price_on_loyalty $data['promotion_shipping_pricing'];
  3590.         if (isset($data["total_pricing"]))
  3591.             $price_on_loyalty $data["total_pricing"];
  3592.         if (isset($data["remise"]))
  3593.             $price_on_loyalty $data['remise'];
  3594.         /**
  3595.          * @var Loyalty
  3596.          */
  3597.         $loyalty =  $this->entityManager->getRepository(Loyalty::class)->findOneBy([
  3598.             "status" => "1"
  3599.         ]);
  3600.         $today = new \DateTime();
  3601.         $countUserCommand count($this->entityManager->getRepository(Command::class)->findBy([
  3602.             'clientId' => $client_id,
  3603.             'state' => '3'
  3604.         ]));
  3605.         $haveAlredyBonus $this->entityManager->getRepository(PayBonus::class)->findOneBy([
  3606.             'clientId' => $client_id
  3607.         ]);
  3608.         if (
  3609.             $haveAlredyBonus == null &&
  3610.             $loyalty != null &&
  3611.             $today >= $loyalty->getStartDate() &&
  3612.             $today <= $loyalty->getEndDate() &&
  3613.             $countUserCommand intval($loyalty->getRequired())
  3614.         ) {
  3615.             if ($loyalty->getType() == '1') {
  3616.                 if (isset($data["promotion_shipping_pricing"]))
  3617.                     $price_on_loyalty 0;
  3618.                 if (isset($data["total_pricing"]))
  3619.                     $price_on_loyalty $promotion_pricing;
  3620.                 if (isset($data["remise"]))
  3621.                     $price_on_loyalty '' . (100 $this->getRemise($total_without_remise$total_pricing));
  3622.             }
  3623.         }
  3624.         return $price_on_loyalty;
  3625.     }
  3626.     private function haversineDistance($lat1$lng1$lat2$lng2): float
  3627.     {
  3628.         $earthRadius 6371;
  3629.         $lat1 deg2rad($lat1);
  3630.         $lng1 deg2rad($lng1);
  3631.         $lat2 deg2rad($lat2);
  3632.         $lng2 deg2rad($lng2);
  3633.         $dlat $lat2 $lat1;
  3634.         $dlng $lng2 $lng1;
  3635.         $a sin($dlat 2) ** cos($lat1) * cos($lat2) * sin($dlng 2) ** 2;
  3636.         $c atan2(sqrt($a), sqrt($a));
  3637.         return $earthRadius $c 1000;
  3638.     }
  3639.     private function checkNumberOfOrderFoUser($id){
  3640.         $client $this->entityManager->getRepository(Client::class)->find($id);
  3641.         if($client){
  3642.             $qb $this->entityManager->createQueryBuilder(); 
  3643.             $qb->select('COUNT(c.id)')
  3644.             ->from(Command::class,'c')
  3645.             ->where('c.clientId = :client_id')
  3646.             ->setParameter('client_id',$id);
  3647.             return (int) $qb->getQuery()->getSingleScalarResult();
  3648.         }else{
  3649.             return -1;
  3650.         }
  3651.     }
  3652.     private function applySubscriptionOnOrder($distance$subscription$prom_ship_price)
  3653.     {
  3654.         $promotion_shipping_pricing $prom_ship_price;
  3655.     
  3656.         try {
  3657.        
  3658.             if (!$subscription || empty($subscription)) {
  3659.                 return $promotion_shipping_pricing;
  3660.             }
  3661.             $pack $subscription['pack'] ?? null;
  3662.             if (!$pack) {
  3663.                 return $promotion_shipping_pricing;
  3664.             }
  3665.             $endDate = isset($subscription['end_date']) ? new DateTime($subscription['end_date']) : null;
  3666.             $now = new DateTime();
  3667.             $isBefore $endDate ? ($now $endDate) : false;
  3668.             $radius_limit = isset($pack['radius_km']) ? floatval($pack['radius_km']) : 0;
  3669.             $delivery_limit = isset($pack['deliverylimit']) ? intval($pack['deliverylimit']) : 0;
  3670.             $usage_count = isset($subscription['alreadyUsed']) ? intval($subscription['alreadyUsed']) : 0;
  3671.             if (!$isBefore) {
  3672.                 return $promotion_shipping_pricing;
  3673.             }
  3674.             if ($distance < (($radius_limit 1000)+100)) {
  3675.                     if ($usage_count $delivery_limit) {
  3676.                         $promotion_shipping_pricing 0;
  3677.                     }
  3678.                 return $promotion_shipping_pricing;
  3679.             }
  3680.         } catch (Exception $e) {
  3681.             error_log("applySubscriptionOnOrder error: " $e->getMessage());
  3682.         }
  3683.     
  3684.         return $promotion_shipping_pricing;
  3685.     }
  3686. }