src/V4Bundle/Controller/OutOfAppOrderController.php line 806

Open in your IDE?
  1. <?php
  2. namespace App\V4Bundle\Controller;
  3. use App\Entity\AdditionalFeeRule;
  4. use App\Entity\AdditionalFees;
  5. use App\Entity\Adresses;
  6. use App\Entity\Billing;
  7. use App\Entity\Client;
  8. use App\Entity\Command;
  9. use App\Entity\Food;
  10. use App\Entity\Livreur;
  11. use App\Entity\LivreurAdditionnalFeeConfig;
  12. use App\Entity\PaymentBill;
  13. use App\Entity\RestaurantConfig;
  14. use App\Entity\Voucher;
  15. use App\Entity\WeatherRule;
  16. use App\Entity\Zone;
  17. use App\V4Bundle\Entity\DeliveryRating as EntityDeliveryRating;
  18. use Doctrine\ORM\EntityManagerInterface;
  19. use Symfony\Component\Serializer\SerializerInterface;
  20. use App\V4Bundle\Controller\BaseController;
  21. use App\V4Bundle\Entity\Billing2;
  22. use App\V4Bundle\Entity\Devices;
  23. use App\V4Bundle\Entity\Employee;
  24. use App\V4Bundle\Entity\Loyalty;
  25. use App\V4Bundle\Entity\PayBonus;
  26. use App\V4Bundle\Entity\PreorderCommandDetails;
  27. use App\V4Bundle\Entity\VoucherOwner;
  28. use App\V4Bundle\Entity\VoucherSubscription;
  29. use App\V4Bundle\Entity\VoucherTransaction;
  30. use App\V4Bundle\Entity\VoucherUsage;
  31. use DateTime;
  32. use Symfony\Component\HttpFoundation\JsonResponse;
  33. use Symfony\Component\HttpFoundation\Request;
  34. use Symfony\Component\HttpFoundation\Response;
  35. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  36. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  37. use Symfony\Component\Routing\Annotation\Route;
  38. use App\V4Bundle\Entity\DeliveryRating;
  39. use App\V4Bundle\Service\AwsS3Service;
  40. use App\V4Bundle\Entity\OutOfAppOrder;
  41. use Symfony\Component\Security\Core\Security;
  42. use Firebase\JWT\JWT;
  43. use Symfony\Component\HttpClient\HttpClient;
  44. use App\Entity\Menu;
  45. use App\Entity\RestoFraisSupp;
  46. use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
  47. use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
  48. use Symfony\Component\Serializer\Serializer;
  49. use App\Enums\AdditionnalFeeType;
  50. use App\Enums\AdditionnalFeeAmountType;
  51. use App\Enums\AdditionalFeeRuleType;
  52. use App\V4Bundle\Entity\DistrictBaricentre;
  53. use Exception;
  54. use Symfony\Component\Mime\Address;
  55. use Symfony\Contracts\HttpClient\HttpClientInterface;
  56. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  57. use Doctrine\DBAL\Connection;
  58. use App\V4Bundle\Entity\Subscription;
  59. use App\V4Bundle\Entity\SharedUser;
  60. use App\V4Bundle\Entity\Pack;
  61. use App\V4Bundle\Entity\UserSusOrd;
  62. use App\V4Bundle\Entity\NewUserPromotion;
  63. class OutOfAppOrderController extends BaseController
  64. {
  65.     protected  $tokenStorage;
  66.     protected   $serializer;
  67.     protected   $entityManager;
  68.     protected   $passwordHasher;
  69.     protected   $awsS3Service;
  70.     protected   $http_client;
  71.     protected $security;
  72.     protected $passwordEncoder;
  73.     protected $connection;
  74.     public function __construct(
  75.         SerializerInterface $serializer,
  76.         EntityManagerInterface $entityManager,
  77.         UserPasswordHasherInterface $passwordHasher,
  78.         TokenStorageInterface $tokenStorage,
  79.         AwsS3Service $awsS3Service,
  80.         Security $security,
  81.         HttpClientInterface $http_client,
  82.         UserPasswordEncoderInterface $passwordEncoder,
  83.         Connection $connection
  84.     ) {
  85.         $this->serializer $serializer;
  86.         $this->entityManager $entityManager;
  87.         $this->passwordHasher $passwordHasher;
  88.         $this->tokenStorage $tokenStorage;
  89.         $this->awsS3Service $awsS3Service;
  90.         $this->security $security;
  91.         $this->http_client $http_client;
  92.         $this->passwordEncoder $passwordEncoder;
  93.         $this->connection $connection;
  94.     }
  95.     // order type of order with order address is 3
  96.     // order type of order without order address is 4
  97.     // order type for colis is 5
  98.     const RESTAURANT_ORDER 1;
  99.     const KABA_COLIS_ORDER 2;
  100.     const OUT_OF_APP_ORDER 3;
  101.     const OUT_OF_APP_WITHOUT_ORDER_ADDRESS 4;
  102.     const KABA_COLIS_SHIPPING 5;
  103.     const KABA_COLIS_FETCHING 6;
  104.     /**
  105.      * @Route("mobile/api/out_of_app_order/billing/get", name="out_of_app_order_billing_get", methods={"POST"}) 
  106.      */
  107.     public function getOutOfAppOrderBilling(Request $request)
  108.     {
  109.         $currentToken $this->get('security.token_storage')->getToken();
  110.         $data json_decode($request->getContent(), true);
  111.         
  112.         if (isset($data['user_id'])) {
  113.             $id $data['user_id'];
  114.             $user $this->entityManager->getRepository(Client::class)->find($id);
  115.             if ($user) {
  116.                 $tokenRequest = new Request(
  117.                     [],
  118.                     [],
  119.                     [],
  120.                     [],
  121.                     [],
  122.                     ['CONTENT_TYPE' => 'application/json'],
  123.                     json_encode(['username' => $user->getUsername()])
  124.                 );
  125.                 $jwtResponse $this->generateJwt($tokenRequest);
  126.                 $jwtData json_decode($jwtResponse->getContent(), true);
  127.                 if (isset($jwtData['token'])) {
  128.                     $currentToken $jwtData['token'];
  129.                 }
  130.             }
  131.         } else {
  132.             $user $currentToken->getUser();
  133.             $id $user->getId();
  134.         }
  135.         if (
  136.             isset($data["order_address"]) &&
  137.             isset($data["shipping_address"]) &&
  138.             $data["order_address"] != null &&
  139.             $data["shipping_address"] != null &&
  140.             isset($data["order_details"])
  141.         ) {
  142.             $nb_order $this->checkNumberOfOrderFoUser($id); 
  143.             
  144.      
  145.              $companie_service_fee 0;
  146.             if (isset($data['companie_service_fee']))
  147.                 $companie_service_fee $data['companie_service_fee'];
  148.             $shipping_address =  $this->entityManager->getRepository(Adresses::class)->find(intval($data["shipping_address"]));
  149.             if ($data['order_address'][0] != 0) {
  150.                 $order_address $this->entityManager->getRepository(Adresses::class)->find(intval($data["order_address"][0]));
  151.             } else {
  152.               $order_address $this->entityManager->getRepository(Adresses::class)->find($data['shipping_address']);   
  153.             }
  154.             $configs_with_voucher $this->configsWithVoucher($data$currentToken$user$order_address$shipping_address);
  155.             $res = [];
  156.             $res["account_balance"] = $this->getBalance($id);
  157.             $res["distance"] = $this->getDistance($order_address->getLocation(), $shipping_address->getLocation());
  158.             $res["shipping_pricing"] = $this->calculate_shipping_price($res["distance"], $currentToken) ;
  159.             $res["kaba_point"] = $this->get_kaba_point($id$res['shipping_pricing']);
  160.             $res['reduced_shipping_price'] = $this->getReducedShippingPrice($data$configs_with_voucher$res['kaba_point'], $res);
  161.             $res['promotion_shipping_pricing'] = $res['reduced_shipping_price'];
  162.           
  163.             //Subscription 
  164.             try{
  165.             if($data['user_abonnement']){
  166.                 $res["promotion_shipping_pricing"] = $this->applySubscriptionOnOrder($res['distance'], $data['user_abonnement'], $res['promotion_shipping_pricing']);
  167.                 $res["reduced_shipping_price"] = $res["promotion_shipping_pricing"];
  168.                 $res['has_subscription'] =  $res["reduced_shipping_price"]==0?true:false;
  169.             }
  170.             }catch(Exception $e){}
  171.             if(!isset($data['user_abonnement'])){
  172.                 try{
  173.                     if($nb_order >= && $nb_order <= 5){
  174.                         $promotion $this->entityManager->getRepository(NewUserPromotion::class)->findAll();
  175.                         if($promotion){
  176.                             if($promotion[0]->getIsActive()==true){
  177.                                 $promotion_for_new_user $promotion[0] ->getValue();
  178.                                 $res["promotion_shipping_pricing"] = $res['shipping_pricing']-$promotion_for_new_user;
  179.                                 $res["reduced_shipping_price"] = $res["promotion_shipping_pricing"];
  180.                                 $res['is_new_user']=true;
  181.                             }else{
  182.                                
  183.                             }
  184.                         }
  185.                     }
  186.                 }catch(Exception $e){}
  187.             }
  188.             $res["command_pricing"] = $this->getCommandPricing($data['order_details']);
  189.             $res['additional_fees'] = $this->getOutOfAppAdditionnalFees($res['shipping_pricing'], $shipping_address$order_address);
  190.             $res['additional_fees_total_price'] = $this->getAdditionalFeesTotalPricing($res["additional_fees"]);
  191.             $res["total_pricing"] = $this->get_total_pricing($res$configs_with_voucher$data$res["kaba_point"], $res["command_pricing"]) + $companie_service_fee;
  192.             $res['total_normal_pricing'] = intval($res["command_pricing"]) + intval($res["shipping_pricing"]) + intval($res['additional_fees_total_price']) + $companie_service_fee;
  193.             $res['total_reduced_pricing'] = intval($res["command_pricing"]) + intval($res["reduced_shipping_price"]) + intval($res['additional_fees_total_price']) + $companie_service_fee;
  194.             $res['promotion_pricing'] = $res['total_reduced_pricing'];
  195.             $res["out_of_range"] = $this->isOutOfRange($res["distance"]);
  196.             $res["pay_at_delivery"] = $data['pay_at_delivery'];
  197.             $res["remise"] = $this->get_remise($id$res$data$res["kaba_point"]);
  198.             $res["trustful"] = $user->getTrustful();
  199.             $res['eligible_vouchers'] = $this->getUserEligibleVoucher($id);
  200.             $res['promotion_pricing'] = $res['total_reduced_pricing'];
  201.             $res['promotion_shipping_pricing'] = $res['reduced_shipping_price'];
  202.                 $sql 'SELECT * FROM devices WHERE id = :id';
  203.                 $device $this->connection->fetchAssociative($sql, ['id' => $user->getDeviceId()]);  
  204.                 $push_token $device['push_token'];
  205.                 try{
  206.                     $notif = [];
  207.                     $notif["error"] = 0;
  208.                     $notif["message"] = "nothing";
  209.                     $notif["data"] = [];
  210.                     $notif["data"]["notification"] = [];
  211.                     $notif["data"]["notification"]["title"] = "ℹ️ Frais supplémentaires";
  212.                     $notif["data"]["notification"]["body"] = "Ce service est sujet de frais supplémentaires";
  213.                     $notif["data"]["notification"]["image_link"] = '';
  214.                     $notif["data"]["notification"]["destination"] = [];
  215.                     $notif["data"]["notification"]["destination"]["type"] = 200;
  216.                     $notif["data"]["notification"]["destination"]["priority"] = 2;
  217.                     $notif["data"]["notification"]["destination"]["amount"] = intval(0);
  218.                     $notif["data"]["notification"]["destination"]["is_out_of_app"] = intval(0);
  219.                     $notif["data"]["notification"]["destination"]["product_id"] = intval(0);
  220.                 //    $this->sendNotificationToDeviceV2([$push_token],"Ce service est sujet de frais supplémentaires",$notif,1);
  221.                 }catch(Exception $e){
  222.                 }
  223.             return new Response($this->serializer->serialize($this->okResponseBlob($res), 'json'));
  224.         } else {
  225.             return new Response($this->serializer->serialize($this->errorResponseBlob('Invalid parameter'), 'json'));
  226.         }
  227.     }
  228.     /**
  229.      * @Route("mobile/api/out_of_app_order/create", name="out_of_app_order_command_create", methods={"POST"})
  230.      */
  231.     public function createOutOfAppOrderWithVoucherAction(Request $request)
  232.     {
  233.         $currentToken $this->get('security.token_storage')->getToken();
  234.         $user $currentToken->getUser();
  235.         $id $user->getId();
  236.         $data json_decode($request->getContent(), true);
  237.         $nb_order $this->checkNumberOfOrderFoUser($id); 
  238.         if($nb_order >= && $nb_order <= 5){
  239.             $data['voucher_id']=null;
  240.             $data['use_kaba_point']=false;
  241.         }
  242.         $is_voucher 0;
  243.         $deliveryRange = [];
  244.           $companie_service_fee 0;
  245.         if (isset($data['companie_service_fee']))
  246.             $companie_service_fee $data['companie_service_fee'];
  247.         $shipping_address =  $this->entityManager->getRepository(Adresses::class)->find(intval($data["shipping_address"]));
  248.         if ($data['order_address'][0] != 0) {
  249.             $order_address $this->entityManager->getRepository(Adresses::class)->find(intval($data["order_address"][0]));
  250.         } else {
  251.             $order_address $this->entityManager->getRepository(Adresses::class)->find($data['shipping_address']);
  252.         }
  253.         $shipping_addres_array $this->getAdress($data["shipping_address"]);
  254.         $order_address_array $this->getAdress($order_address->getId());
  255.         if ($order_address_array == -1)
  256.             return new Response($this->serializer->serialize($this->errorResponseBlob(null301), 'json'));
  257.         if ($shipping_addres_array == -1)
  258.             return new Response($this->serializer->serialize($this->errorResponseBlob(null304), 'json'));
  259.         $voucher_id null;
  260.         if (isset($data["voucher_id"]) && $data["voucher_id"] != null) {
  261.             $voucher_id intval($data["voucher_id"]);
  262.             $is_voucher 1;
  263.         }
  264.         $use_kaba_point false;
  265.         if (isset($data["use_kaba_point"]) && $data["use_kaba_point"] != null)
  266.             $use_kaba_point $data["use_kaba_point"];
  267.         $command_details $this->getCommandDetails($data['order_details'], $order_address$shipping_address$data['voucher_id'], $id$data['use_kaba_point']);
  268.         $data["food_command"] = $command_details["foods"];
  269.         $details "Livraison de " " " $command_details["food_litteral"];
  270.         if (!($this->checkValidUser($id)))
  271.             return new Response($this->serializer->serialize($this->errorResponseBlob(null306), 'json'));
  272.         $master_key md5('kabapeur');
  273.         if (!(isset($data['master_key']) && $data['master_key'] == $master_key)) {
  274.             if (!($this->checkTransactionPassword($id$data["transaction_password"])))
  275.                 return new Response($this->serializer->serialize($this->errorResponseBlob(null300), 'json'));
  276.         }
  277.         $files $request->files->all();
  278.         $isFirstCommandBonusApply $this->isFirstCommandBonusApply($id);
  279.         if ($isFirstCommandBonusApply['response'] && $isFirstCommandBonusApply['type'] == '1') {
  280.             $haveBillingDiscount true;
  281.         } else {
  282.             $haveBillingDiscount $command_details["haveBillingDiscount"];
  283.         }
  284.         $client =  $this->entityManager->getRepository(Client::class)->find($id);
  285.         $command = new Command();
  286.         $em $this->entityManager;
  287.         $word false;
  288.         while ($word == false) {
  289.             $word $this->generateWord();
  290.         }
  291.         $command->setPassPhrase($word);
  292.         if ($command_details["is_kaba_point_used"]) {
  293.             $kabaPointTransaction $this->debitKabaPointAccount($idintval($command_details["kaba_point_used_amount"]));
  294.             if ($kabaPointTransaction['state']) {
  295.                 $command->setKabaPoint(intval($kabaPointTransaction["transaction"]["id"]));
  296.                 $command->setKabaPointAmount(intval($command_details["kaba_point_used_amount"]));
  297.             } else {
  298.                 $command_details["food_billing"] += intval($command_details["kaba_point_used_amount"]);
  299.                 $command_details["email_shipping_pricing"] += intval($command_details["kaba_point_used_amount"]) ;
  300.                 $command_details["phoneNumber_shipping_pricing"] += intval($command_details["kaba_point_used_amount"]) ;
  301.             }
  302.         }
  303.         $is_subscription_discount_allowed =false;
  304.         $realyShippingPrice $command_details["voucher_pricing"]["shipping_pricing"] ;
  305.         if (intval($data['order_type']) == || intval($data['order_type']) == 6) {
  306.             $resto $this->entityManager->getRepository(RestaurantConfig::class)->findOneBy(['username' => "kaba_colis"]);
  307.             $food_command $this->createColisFoods($command_details['foods']);
  308.         } else if (intval($data['order_type']) == || intval($data['order_type']) == 4) {
  309.             $resto $this->entityManager->getRepository(RestaurantConfig::class)->findOneBy(['username' => "hors_appli"]);
  310.             $food_command $this->createHorsAppliFoods($command_details['foods']);
  311.         }
  312.         $command->setFoodCommand($food_command);
  313.         $command->setOrderDetails($data["order_details"]);
  314.         $command->setPayAtDelivery($data["pay_at_delivery"]);
  315.         $command->setClientId($id);
  316.         $command->setClient($user);
  317.         $command->setState(-1);
  318.         $command->setOrderShippingAddress($order_address_array);
  319.         $command->setShippingAddress($shipping_addres_array);
  320.         $command->setHaveBillingDiscount($haveBillingDiscount);
  321.         $command->setExtraShippingPricing($command_details["extra_shipping_pricing"] > $realyShippingPrice $command_details["extra_shipping_pricing"]);
  322.         $command->setBaseShippingPricing($command_details["base_shipping_pricing"]);
  323.         $command->setEmailAccountShippingPricing($command_details["email_shipping_pricing"]);
  324.         $command->setPhoneNumberAccountShippingPricing($command_details["phoneNumber_shipping_pricing"]);
  325.         $command->setShippingPricing($realyShippingPrice);
  326.         //Subscription 
  327.         try{
  328.             if($data['user_abonnement']){
  329.                 $promotion_shipping_pricing $this->applySubscriptionOnOrder($this->getDistance($shipping_addres_array['location'], $order_address_array['location']),$data['user_abonnement'],$command->getShippingPricing());
  330.                 if($promotion_shipping_pricing==0){
  331.                     $command->setHaveBillingDiscount(true);
  332.                     $is_subscription_discount_allowed true;
  333.                     $command->setShippingPricing(0);
  334.                 }else{
  335.                     $command->setHaveBillingDiscount(false);
  336.                 }
  337.             }
  338.         }catch(Exception $e){
  339.             
  340.         }
  341.         if(!isset($data['user_abonnement'])){
  342.             try{
  343.                 if($nb_order >= && $nb_order <= 5){
  344.                     $promotion $this->entityManager->getRepository(NewUserPromotion::class)->findAll();
  345.                     if($promotion){
  346.                         if($promotion[0] ->getIsActive()==true){
  347.                             $promotion_for_new_user $promotion[0] ->getValue();
  348.                             $command->setHaveBillingDiscount(true);
  349.                             $command->setShippingPricing($realyShippingPrice-$promotion_for_new_user);
  350.                          }
  351.                     }
  352.                 }
  353.             }catch(Exception $e){
  354.                 
  355.             }
  356.         }
  357.         $command->setOrderType($data['order_type']);
  358.         $command->setStartTime(date('Y-m-d H:i:s'));
  359.         $command->setStartDate(date('Y-m-d'));
  360.         $command->setLastUpdate(date('Y-m-d H:i:s'));
  361.         $command->setRestaurant($resto);
  362.         $command->setRestaurantId($resto->getId());
  363.         $command->setPhoneNumber($data['phone_number']);
  364.         $client_commands $this->entityManager->getRepository(Command::class)->findBy([
  365.             'clientId' => $id,
  366.         ]);
  367.         if (count($client_commands) > 0)
  368.             $command->setIsFirstOrder(false);
  369.         else
  370.             $command->setIsFirstOrder(true);
  371.         if ($command_details['is_voucher_used'])
  372.             $command->setHasVoucher(true);
  373.         else
  374.             $command->setHasVoucher(false);
  375.         if (isset($data["infos"]) && $data["infos"] != null)
  376.             $command->setInfos($data["infos"]);
  377.         if (isset($data['infos_image'])) {
  378.             $command->setAdditionnalInfoImage($data['infos_image']);
  379.         }
  380.         $em->persist($command);
  381.         $em->flush();
  382.         if (isset($data['device'])) {
  383.             if ($data["device"]["push_token"] != null) {
  384.                 $device =  $this->entityManager->getRepository(Devices::class)->findOneBy([
  385.                     'pushToken' => $data["device"]["push_token"]
  386.                 ]);
  387.                 if ($device != null) {
  388.                     $client->setDeviceId($device->getId());
  389.                 } else {
  390.                     $device_id $this->createDevice($data["device"], 1);
  391.                     $client->setDeviceId($device_id);
  392.                 }
  393.             }
  394.         }
  395.         $temp_foodPricing 0;
  396.         $tem_shippingPricing 0;
  397.         if ($data["pay_at_delivery"] == true) {
  398.             if ($command_details['is_voucher_used']) {
  399.                 $pay_at_delivery_total_price intval($command_details["voucher_pricing"]["total_pricing"]);
  400.                 if ($isFirstCommandBonusApply['response']) {
  401.                     $pay_at_delivery_total_price -= intval($command_details["voucher_pricing"]["shipping_pricing"]);
  402.                     $temp_foodPricing $pay_at_delivery_total_price;
  403.                     $tem_shippingPricing intval($command_details["voucher_pricing"]["shipping_pricing"]);
  404.                 }
  405.             } else {
  406.                 $pay_at_delivery_total_price intval($command_details["without_promo"]["total"]);
  407.                 if ($isFirstCommandBonusApply['response']) {
  408.                     $pay_at_delivery_total_price -= intval($command_details["without_promo"]["billing"]);
  409.                     $temp_foodPricing $pay_at_delivery_total_price;
  410.                     $tem_shippingPricing intval($command_details["without_promo"]["billing"]);
  411.                 }
  412.             }
  413.             $res $this->debitClientAction($id$pay_at_delivery_total_price$details0$command->getId());
  414.             if ($res) {
  415.                 $command->setState(0);
  416.                 $em->flush();
  417.                 $isFirstCommandBonusApply['response'] ? $this->applyFirstCommandProccess($id$command->getId(), $temp_foodPricing$tem_shippingPricing) : '';
  418.             } else {
  419.                 $em->remove($command);
  420.                 $em->flush();
  421.             }
  422.         } else if ($data["pay_at_delivery"] == false) {
  423.             return new JsonResponse(['error' => "Action not allowed"]);
  424.         }
  425.         if ($is_voucher == && ($command_details["voucher_pricing"]["valid"] == true || $command_details["is_voucher_used"])) {
  426.             $voucher_id intval($data["voucher_id"]);
  427.             $voucher $this->entityManager->getRepository(Voucher::class)->find($voucher_id);
  428.             $voucher_subs =  $this->entityManager->getRepository(VoucherSubscription::class)->findOneBy([
  429.                 'userId' => $id,
  430.                 'voucherId' => $voucher_id,
  431.             ]);
  432.             if ($voucher_subs != null) {
  433.                 $usage_count count($this->entityManager->getRepository(VoucherUsage::class)->findBy([
  434.                     'userId' => $id,
  435.                     'voucherId' => $voucher_id,
  436.                     'isReallyUsed' => 1
  437.                 ]));
  438.                 if ($voucher != null) {
  439.                     if (($usage_count 1) >= intval($voucher->getUseCount())) {
  440.                         $voucher_subs->setState(1);
  441.                     }
  442.                     $voucher_subs->setUseCount($usage_count 1);
  443.                     $new_usage = new VoucherUsage();
  444.                     $new_usage->setUserId($id);
  445.                     $new_usage->setVoucherId($voucher_id);
  446.                     $new_usage->setCommandId($command->getId());
  447.                     $new_usage->setIsReallyUsed(1);
  448.                     $new_usage->setCreatedAt(strtotime(date('Y-m-d H:i:s')));
  449.                     $em->persist($new_usage);
  450.                     $reward 0;
  451.                     $check_voucher_owners $this->entityManager->getRepository(VoucherOwner::class)->findBy([
  452.                         'voucherId' => $voucher_id
  453.                     ]);
  454.                     if ($check_voucher_owners != null) {
  455.                         if ($command_details["voucher_pricing"]["owner"]["is_rewarded"] == 1) {
  456.                             $reward $command_details["voucher_pricing"]["owner"]["reward_cash_value"];
  457.                         }
  458.                         if ($reward 0) {
  459.                             foreach ($check_voucher_owners as $owner) {
  460.                                 $voucher_transaction = new VoucherTransaction();
  461.                                 $voucher_transaction->setUserId($owner->getUserId());
  462.                                 $voucher_transaction->setVoucherId($voucher_id);
  463.                                 $voucher_transaction->setValue($reward);
  464.                                 $voucher_transaction->setType(1);
  465.                                 $voucher_transaction->setCommandId($command->getId());
  466.                                 $voucher_transaction->setState(0);
  467.                                 $voucher_transaction->setCreatedAt(strtotime(date('Y-m-d H:i:s')));
  468.                                 $voucher_transaction->setUpdatedAt(strtotime(date('Y-m-d H:i:s')));
  469.                                 $em->persist($voucher_transaction);
  470.                             }
  471.                         }
  472.                     }
  473.                 }
  474.             }
  475.             $em->flush();
  476.         }
  477.         $jsonData json_encode([
  478.             "order_details" => $command->getOrderDetails(),
  479.             "order_address" => $data['order_address'],
  480.             "shipping_address" => $data['shipping_address'],
  481.             "voucher_id" => $voucher_id,
  482.             "use_kaba_point" => $use_kaba_point,
  483.             "pay_at_delivery" => $data['pay_at_delivery'],
  484.             "companie_service_fee" => $companie_service_fee
  485.         ]);
  486.         $Billingrequest = new Request(
  487.             [],
  488.             [],
  489.             [],
  490.             [],
  491.             [],
  492.             ['CONTENT_TYPE' => 'application/json'],
  493.             $jsonData
  494.         );
  495.         $getBilling $this->getOutOfAppOrderBilling($Billingrequest);
  496.         $getBillingContent $getBilling->getContent();
  497.         $getBillingData json_decode($getBillingContenttrue);
  498.         $this->createPaymentBill($getBillingData['data'], $command->getId());
  499.         $client_balance $this->getBalance($id);
  500.         $data = [];
  501.         $data["balance"] = $client_balance;
  502.         $data["pre_order"] = false;
  503.         $data["pre_order_hour"] = $deliveryRange;
  504.         $data["voucher_data"] = $command_details["voucher_pricing"];
  505.         $data["command_details"] = $getBillingData;
  506.         $response["error"] = 0;
  507.         $response["code"] = 200;
  508.         $response["message"] = "200 OK";
  509.         $response["data"] = [];
  510.         $response["data"]['distance'] = $getBillingData['data']['distance'];
  511.         $response["data"]['shipping_pricing'] = $getBillingData['data']['shipping_pricing'];
  512.         $response["data"]['command_pricing'] = $getBillingData['data']['command_pricing'];
  513.         $response["data"]['additional_fees'] = $getBillingData['data']['additional_fees_total_price'];
  514.         $response["data"]['out_of_range'] = $getBillingData['data']['out_of_range'];
  515.         $response["data"]['total_pricing'] = $getBillingData['data']['total_pricing'];
  516.         $response["data"]["command_id"] = $command->getId();
  517.         $pusher $this->getPusher();
  518.         $message = [];
  519.         $message['id'] = $command->getId();
  520.         $message['state'] = $command->getState();
  521.         $pusher->trigger($this->getParameter('PUSHER_APP_CHANNEL'), BaseController::NEW_COMMAND$message);
  522.         return new JsonResponse(json_decode($this->serializer->serialize($getBillingData'json')), 200);
  523.     }
  524.     /**
  525.      * @Route("mobile/api/out_of_app_order/get/details", name="out_of_app_order_get_details", methods={"POST"})
  526.      */
  527.     public function getOutOfAppOrderDetailsWithVoucher(Request $request)
  528.     {
  529.         $currentToken $this->get('security.token_storage')->getToken();
  530.         $id $currentToken->getUser()->getId();
  531.         $json_data $request->getContent();
  532.         $data json_decode($json_datatrue);
  533.         $command_id $data["command_id"];
  534.         $command $this->entityManager->getRepository(Command::class)->findOneBy([
  535.             'id' => intval($command_id),
  536.         ]);
  537.         $companie_service_fee 0;
  538.         if (isset($data['companie_service_fee']))
  539.             $companie_service_fee $data['companie_service_fee'];
  540.         if ($command == null || ($command->getClient() != null && $command->getClientId() != $id)) {
  541.             return new Response($this->serializer->serialize($this->errorResponseBlob([]), 'json'), 200);
  542.         }
  543.         $vouch $this->madeUpCommandItemWithVoucher($command);
  544.         if ($vouch["voucher_entity"] != []) {
  545.             $vouch["voucher_entity"]["already_used_count"] = count($this->entityManager->getRepository(VoucherUsage::class)->findBy([
  546.                 'voucherId' => $vouch["voucher_entity"]["id"],
  547.                 'userId' => $id,
  548.                 'isReallyUsed' => 1
  549.             ]));
  550.         }
  551.         $data["command"] = $vouch;
  552.         $payment_bill $this->entityManager->getRepository(PaymentBill::class)->findOneBy(['command' => $command->getId()]);
  553.         if ($payment_bill) {
  554.             $total_additionnal_fee $payment_bill->getAdditionalFeesTotalPrice();
  555.             $data["command"]["total_pricing"] = $data["command"]["total_pricing"] + $total_additionnal_fee  $companie_service_fee;
  556.             $data["command"]["preorder_total_pricing"] = $data["command"]["preorder_total_pricing"] + $total_additionnal_fee  $companie_service_fee;
  557.             $data["command"]["promotion_total_pricing"] = $total_additionnal_fee $data["command"]["promotion_total_pricing"]  + $companie_service_fee;
  558.             $data["command"]["additionnal_fee"] = $total_additionnal_fee;
  559.             $data["command"]["remise"] = '' . (100 $this->getRemise($data["command"]["total_pricing"], $data["command"]["promotion_total_pricing"]));
  560.         }
  561.         $rating 0;
  562.         $comment '';
  563.         $repo $this->entityManager->getRepository(EntityDeliveryRating::class);
  564.         $rate $repo->findOneBy([
  565.             'commandId' => $command->getId()
  566.         ]);
  567.         if ($rate != null) {
  568.             $rating $rate->getRating()??0;
  569.             $comment $rate->getComment();
  570.         }
  571.         $data["command"]["rating"] = $rating;
  572.         $data["command"]["comment"] = $comment;
  573.         return new Response($this->serializer->serialize($this->okResponseBlob($data), 'json'), 200);
  574.     }
  575.     /**
  576.      * @Route("mobile/api/out_of_app_order/all/get", name="out_of_app_order_get_all_orders", methods={"POST"})
  577.      */
  578.     public function getApiAllCommandWithVoucherAction()
  579.     {
  580.         $currentToken $this->get('security.token_storage')->getToken();
  581.         $id $currentToken->getUser()->getId();
  582.         $repository $this->entityManager->getRepository(Command::class);
  583.         $start_date date('Y-m-d'strtotime('-90 days'));
  584.         $end date('Y-m-d'strtotime('+1 day'));
  585.         $period = new \DatePeriod(
  586.             new \DateTime($start_date),
  587.             new \DateInterval('P1D'),
  588.             new  \DateTime($end)
  589.         );
  590.         $date_array = [];
  591.         foreach ($period as $key => $value) {
  592.             array_push($date_array$value->format('Y-m-d'));
  593.         }
  594.         $commands $repository->createQueryBuilder('c')
  595.             ->where('c.clientId = :clientId')
  596.             ->andWhere('c.startDate IN (:dateArray)')
  597.             ->andWhere('c.order_type = 3 OR c.order_type = 4 OR c.order_type = 5 OR c.order_type = 6')
  598.             ->setParameter('clientId'$id)
  599.             ->setParameter('dateArray'$date_array)
  600.             ->orderBy('c.lastUpdate''DESC')
  601.             ->getQuery()
  602.             ->getResult();
  603.         if ($commands != null) {
  604.             $command_array = [];
  605.             $command_array["commands"] = [];
  606.             foreach ($commands as $command) {
  607.                 $tmp $this->forMobileWithVoucherCommandToArray($command);
  608.                 $payment_bill $this->entityManager->getRepository(PaymentBill::class)->findOneBy(['command' => $command->getId()]);
  609.                 if ($payment_bill) {
  610.                     $total_additionnal_fee $payment_bill->getAdditionalFeesTotalPrice();
  611.                     $tmp["total_pricing"] = $tmp["total_pricing"] + $total_additionnal_fee;
  612.                     $tmp["preorder_total_pricing"] = $tmp["preorder_total_pricing"] + $total_additionnal_fee;
  613.                     $tmp["promotion_total_pricing"] = $total_additionnal_fee $tmp["promotion_total_pricing"];
  614.                     $tmp["additionnal_fee"] = $total_additionnal_fee;
  615.                 }
  616.                 array_push($command_array["commands"], $tmp);
  617.             }
  618.             return new Response($this->serializer->serialize($this->okResponseBlob($command_array), 'json'));
  619.         } else {
  620.             return new Response($this->serializer->serialize($this->okResponseBlob([]), 'json'));
  621.         }
  622.     }
  623.     /**
  624.      * @Route("mobile/api/out_of_app_order/get", name="user_mobile_out_of_app_order_get", methods={"POST"})
  625.      */
  626.     public function getApiOutOfAppWithVoucherAction()
  627.     {
  628.         $currentToken $this->get('security.token_storage')->getToken();
  629.         $id $currentToken->getUser()->getId();
  630.         $query $this->entityManager->createQuery('
  631.         SELECT c FROM App:Command c 
  632.         WHERE c.clientId = :id 
  633.         AND ((c.startDate = :startDate) 
  634.             OR (c.startDate < :startDate AND c.state < :deliveredState))
  635.         AND (c.order_type = 3 OR c.order_type = 4 OR c.order_type = 5 OR c.order_type = 6) 
  636.         AND c.order_type IS NOT NULL
  637.         ORDER BY c.lastUpdate DESC
  638.               ')
  639.             ->setParameter('startDate'date("Y-m-d"))
  640.             ->setParameter('deliveredState'3)
  641.             ->setParameter('id'intval($id));
  642.         $commands $query->execute();
  643.         $command_array = [];
  644.         $command_array["commands"] = [];
  645.         if ($commands != null) {
  646.             foreach ($commands as $command) {
  647.                 $tmp $this->forMobileWithVoucherCommandToArray($command);
  648.                 $payment_bill $this->entityManager->getRepository(PaymentBill::class)->findOneBy(['command' => $tmp["id"]]);
  649.                 if ($payment_bill) {
  650.                     $total_additionnal_fee $payment_bill->getAdditionalFeesTotalPrice();
  651.                     $tmp["total_pricing"] = $tmp["total_pricing"] + $total_additionnal_fee;
  652.                     $tmp["preorder_total_pricing"] = $tmp["preorder_total_pricing"] + $total_additionnal_fee;
  653.                     $tmp["promotion_total_pricing"] = $total_additionnal_fee $tmp["promotion_total_pricing"];
  654.                 }
  655.                 array_push($command_array["commands"], $tmp);
  656.             }
  657.             return new Response($this->serializer->serialize($this->okResponseBlob($command_array), 'json'));
  658.         } else {
  659.             return new Response($this->serializer->serialize($this->okResponseBlob($command_array), 'json'));
  660.         }
  661.     }
  662.     /**
  663.      * @Route("mobile/api/out_of_app_order/image/upload", name="user_mobile_out_of_app_order_image_upload", methods={"POST"})
  664.      */
  665.     public function uploadMultipleImages(Request $request)
  666.     {
  667.         return $this->processImageUpload($request);
  668.     }
  669.     /**
  670.      * @Route("mobile/api/v4/livreur/out_of_app_order/receipt/upload", name="livreur_mobile_out_of_app_order_receipt_upload", methods={"POST"})
  671.      */
  672.     public function uploadReceiptImages(Request $request)
  673.     {
  674.         return $this->processImageUpload($request);
  675.     }
  676.     /**
  677.      * @Route("mobile/api/out_of_app_order/districts/get", name="out_of_app_order_get_all_districts", methods={"POST"})
  678.      */
  679.     public function getDistrict()
  680.     {
  681.         $currentToken $this->get('security.token_storage')->getToken();
  682.         $districts $this->entityManager->getRepository(DistrictBaricentre::class)->findAll();
  683.         $districts_array = [];
  684.         foreach ($districts as $district) {
  685.             $district_content = [
  686.                 "name" => $district->getName(),
  687.                 "geopoint" => $district->getGeopoint(),
  688.                 "state" => $district->getState(),
  689.             ];
  690.             $address $this->entityManager->getRepository(Adresses::class)->findOneBy(["name" => $district_content['name']]);
  691.             if (!$address) {
  692.                 $address = new Adresses();
  693.                 $address->setDescription("Le quartier de " $district_content['name']);
  694.                 $address->setName($district_content['name']);
  695.                 $address->setPhoneNumber("91215301");
  696.                 $address->setLocation($district->getGeopoint());
  697.                 $address->setNear("Se situe à lomé");
  698.                 $address->setQuartier($district->getName());
  699.                 $address->setDescriptionDetails("Le quartier de " $district_content['name']);
  700.                 $user $this->entityManager->getRepository(Client::class)->findOneBy(["username" => "91215301"]);
  701.                 if (!$user) {
  702.                     $user = new Client();
  703.                     $hash $this->passwordEncoder->encodePassword(new \App\Entity\Client(), "1234");
  704.                     $user->setPassword($hash);
  705.                     $user->setUsername("91215301");
  706.                     $user->setNickName('Kaba 91215301');
  707.                     $user->setSalt('');
  708.                     $user->setIsSet(0);
  709.                     $user->setRoles(array('ROLE_USER'));
  710.                     $user->setGender(0);
  711.                     $user->setProfilePicture('defult.jpeg');
  712.                     $user->setThemePicture('default.jpeg');
  713.                     $user->setCreatedAt(strtotime(date("Y-m-d H:i:s")));
  714.                     $user->setCreatedDate(date("Y-m-d"));
  715.                     $user->setLastUpdate(date("Y-m-d H:i:s"));
  716.                     $user->setBirthday('');
  717.                     $user->setEnabled(1);
  718.                     $user->setTrustful(1);
  719.                     $user->setIsSponsored(0);
  720.                     $this->entityManager->persist($user);
  721.                     $this->entityManager->flush($user);
  722.                 }
  723.                 $address->setUserId($user->getId());
  724.                 $address->setUpdatedAt(date("Y-m-d H:i:s"));
  725.                 $address->setState(1);
  726.                 $this->entityManager->persist($address);
  727.                 $this->entityManager->flush($address);
  728.             }
  729.             $district_content['address_id'] = $address->getId();
  730.             $district_content['description'] = $address->getDescription();
  731.             array_push($districts_array$district_content);
  732.         }
  733.         return new JsonResponse(['districts' => $districts_array]);
  734.     }
  735.     /**
  736.      * @Route("mobile/api/out_of_app_order/shipping_price_range/get", name="out_of_app_order_get_shipping_price_range", methods={"POST"})
  737.      */
  738.     public function getShippingRange(){
  739.         $db_billing =  $this->entityManager->getRepository(Billing::class)->findAll();
  740.         $minimum 0;
  741.         $maximum 0;
  742.         if ($db_billing != null) {
  743.             foreach ($db_billing as $db_billing_item) {
  744.                 if (intval($db_billing_item->getRangeStart())==0) {
  745.                     $minimum $db_billing_item->getValue();
  746.                 }
  747.                 if (intval($db_billing_item->getRangeStart())==5) {
  748.                     $maximum $db_billing_item->getValue();
  749.                 }
  750.             }
  751.         }
  752.         return new JsonResponse(['range'=>['minimum'=>$minimum,'maximum'=>$maximum]]);
  753.     }
  754.     private function get_remise($client_id$res$data$kabaPoint)
  755.     {
  756.         $remise 0;
  757.         $total_without_remise intval($res["command_pricing"]) + intval($res["shipping_pricing"]) + $res['additional_fees_total_price'];
  758.         $total_with_remise intval($res["promotion_pricing"]) + intval($res["promotion_shipping_pricing"]) + $res['additional_fees_total_price'];
  759.         $total_pricing $res["total_normal_pricing"];
  760.         $remise '' 100 $this->getRemise($total_without_remise$total_with_remise);
  761.         if (isset($data["voucher_id"]) && $data["voucher_id"] != null) {
  762.             $total_with_voucher_remise intval($res["total_pricing"]);
  763.             $remise '' 100 $this->getRemise($total_without_remise$total_with_voucher_remise);
  764.         }
  765.         if (isset($data['use_kaba_point']) && $data['use_kaba_point']) {
  766.             $amount intval($kabaPoint["amount_to_reduce"]);
  767.             if ($amount >= $res["shipping_pricing"]) {
  768.                 $total_pricing $res["promotion_pricing"];
  769.                 $remise  '' 100 $this->getRemise($total_without_remise$total_pricing);
  770.             } else {
  771.                 $promotion_shipping_pricing $res["shipping_pricing"] - $amount;
  772.                 $total_pricing $res["promotion_pricing"] + $promotion_shipping_pricing;
  773.                 $remise  '' 100 $this->getRemise($total_without_remise$total_pricing);
  774.             }
  775.         }
  776.         $type = [];
  777.         $type['remise'] = $remise;
  778.         $remise $this->price_based_on_loyalty($client_id$typenull$total_without_remise$total_pricing);
  779.         return $remise "";
  780.     }
  781.     private function price_based_on_loyalty($client_id$data$promotion_pricing null$total_without_remise null$total_pricing null)
  782.     {
  783.         $price_on_loyalty 0;
  784.         if (isset($data["promotion_shipping_pricing"]))
  785.             $price_on_loyalty $data['promotion_shipping_pricing'];
  786.         if (isset($data["total_pricing"]))
  787.             $price_on_loyalty $data["total_pricing"];
  788.         if (isset($data["remise"]))
  789.             $price_on_loyalty $data['remise'];
  790.         /**
  791.          * @var Loyalty
  792.          */
  793.         $loyalty =  $this->entityManager->getRepository(Loyalty::class)->findOneBy([
  794.             "status" => "1"
  795.         ]);
  796.         $today = new \DateTime();
  797.         $countUserCommand count($this->entityManager->getRepository(Command::class)->findBy([
  798.             'clientId' => $client_id,
  799.             'state' => '3'
  800.         ]));
  801.         $haveAlredyBonus $this->entityManager->getRepository(PayBonus::class)->findOneBy([
  802.             'clientId' => $client_id
  803.         ]);
  804.         if (
  805.             $haveAlredyBonus == null &&
  806.             $loyalty != null &&
  807.             $today >= $loyalty->getStartDate() &&
  808.             $today <= $loyalty->getEndDate() &&
  809.             $countUserCommand intval($loyalty->getRequired())
  810.         ) {
  811.             if ($loyalty->getType() == '1') {
  812.                 if (isset($data["promotion_shipping_pricing"]))
  813.                     $price_on_loyalty 0;
  814.                 if (isset($data["total_pricing"]))
  815.                     $price_on_loyalty $promotion_pricing;
  816.                 if (isset($data["remise"]))
  817.                     $price_on_loyalty '' . (100 $this->getRemise($total_without_remise$total_pricing));
  818.             }
  819.         }
  820.         return $price_on_loyalty;
  821.     }
  822.     private function processImageUpload(Request $request)
  823.     {
  824.         $data json_decode($request->getContent(), true);
  825.         if (!isset($data['orderDetails'])) {
  826.             return new JsonResponse(['error' => 'Invalid order details'], Response::HTTP_BAD_REQUEST);
  827.         }
  828.         if (!is_array($data['orderDetails'])) {
  829.             $data['orderDetails'] = [$data['orderDetails']];
  830.         }
  831.         $folder 'out_of_app_orders';
  832.         foreach ($data['orderDetails'] as &$order) {
  833.             if (!isset($order['image']) || empty($order['image'])) {
  834.                 continue;
  835.             }
  836.             try {
  837.                 $order['image'] = $this->uploadImageToS3($order['image'], $folder);
  838.             } catch (\Exception $e) {
  839.                 return new JsonResponse(['error' => 'Error uploading file: ' $e->getMessage()], Response::HTTP_INTERNAL_SERVER_ERROR);
  840.             }
  841.         }
  842.         return new JsonResponse([
  843.             'message' => 'Upload successful',
  844.             'orders' => $data['orderDetails']
  845.         ], Response::HTTP_OK);
  846.     }
  847.     private function uploadImageToS3($base64Image$folder)
  848.     {
  849.         $imageData base64_decode($base64Image);
  850.         $tempFile tempnam(sys_get_temp_dir(), 'aws_upload_');
  851.         file_put_contents($tempFile$imageData);
  852.         $finfo finfo_open(FILEINFO_MIME_TYPE);
  853.         $mimeType finfo_file($finfo$tempFile);
  854.         finfo_close($finfo);
  855.         switch ($mimeType) {
  856.             case 'image/jpg':
  857.             case 'image/jpeg':
  858.                 $extension 'jpg';
  859.                 break;
  860.             case 'image/png':
  861.                 $extension 'png';
  862.                 break;
  863.             case 'image/gif':
  864.                 $extension 'gif';
  865.                 break;
  866.             default:
  867.                 $extension 'jpg';
  868.         }
  869.         $fileName time() . '_' uniqid() . '.' $extension;
  870.         $s3Path $folder '/' $fileName;
  871.         $url $this->awsS3Service->uploadFile($tempFile$folder$fileName);
  872.         unlink($tempFile);
  873.         return $url;
  874.     }
  875.     //API FOR COMPANIES OUT OF APP ORDERS 
  876.     /**
  877.      * @Route("out_of_app/api/order/billing/get", name="out_of_app_api_order_billing_get", methods={"POST"})
  878.      */
  879.     public function OutOfOrderGetBilling(Request $request)
  880.     {
  881.         $currentToken $this->get('security.token_storage')->getToken();
  882.         $userId $currentToken->getUser()->getId();
  883.         $data json_decode($request->getContent(), 'true');
  884.         if (isset($data['order_details']) && isset($data['order_address']) && isset($data['shipping_address'])) {
  885.             $user $this->entityManager->getRepository(Client::class)->findOneBy(['id' => $userId]);
  886.             $OrderAddress = new Adresses();
  887.             $OrderAddress->setDescription("this my description and its an order address");
  888.             $OrderAddress->setName("no name yet");
  889.             $OrderAddress->setPhoneNumber($user->getPhoneNumber());
  890.             $OrderAddress->setLocation($data['order_address']);
  891.             $OrderAddress->setNear("near location");
  892.             $OrderAddress->setQuartier("Nothing here");
  893.             $OrderAddress->setDescriptionDetails("decription details of mine");
  894.             $OrderAddress->setUserId($userId);
  895.             $OrderAddress->setUpdatedAt(date("Y-m-d H:i:s"));
  896.             $OrderAddress->setState(1);
  897.             $this->entityManager->persist($OrderAddress);
  898.             $this->entityManager->flush($OrderAddress);
  899.             $shippingAddress = new Adresses();
  900.             $shippingAddress->setDescription("this my description and its a shipping address");
  901.             $shippingAddress->setName("no name yet");
  902.             $shippingAddress->setPhoneNumber($user->getPhoneNumber());
  903.             $shippingAddress->setLocation($data['shipping_address']);
  904.             $shippingAddress->setNear("near location");
  905.             $shippingAddress->setQuartier("Nothing here");
  906.             $shippingAddress->setDescriptionDetails("decription details of mine");
  907.             $shippingAddress->setUserId($userId);
  908.             $shippingAddress->setUpdatedAt(date("Y-m-d H:i:s"));
  909.             $shippingAddress->setState(1);
  910.             $this->entityManager->persist($shippingAddress);
  911.             $this->entityManager->flush($shippingAddress);
  912.             try {
  913.                 $jsonData json_encode([
  914.                     "order_details" => $data['order_details'],
  915.                     "order_address" => [$OrderAddress->getId()],
  916.                     "shipping_address" => $shippingAddress->getId(),
  917.                     "voucher_id" => null,
  918.                     "use_kaba_point" => false,
  919.                     "pay_at_delivery" => true,
  920.                     "companie_service_fee" => $data['service_fee']
  921.                 ]);
  922.                 $Billingrequest = new Request(
  923.                     [],
  924.                     [],
  925.                     [],
  926.                     [],
  927.                     [],
  928.                     [
  929.                         'CONTENT_TYPE' => 'application/json'
  930.                     ],
  931.                     $jsonData
  932.                 );
  933.                 $getBilling $this->getOutOfAppOrderBilling($Billingrequest);
  934.                 $getBillingContent $getBilling->getContent();
  935.                 $getBillingData json_decode($getBillingContenttrue);
  936.                 $this->entityManager->remove($OrderAddress);
  937.                 $this->entityManager->remove($shippingAddress);
  938.                 $res = [];
  939.                 $res['distance'] = $getBillingData['data']['distance'];
  940.                 $res['shipping_pricing'] = $getBillingData['data']['shipping_pricing'];
  941.                 $res['command_pricing'] = $getBillingData['data']['command_pricing'];
  942.                 $res['additional_fees'] = $getBillingData['data']['additional_fees_total_price'];
  943.                 $res['out_of_range'] = $getBillingData['data']['out_of_range'];
  944.                 $res['total_pricing'] = $getBillingData['data']['total_pricing'];
  945.                 $res['company_commission_fee'] = $data['service_fee'];
  946.                 return  new Response($this->serializer->serialize($this->okResponseBlob($res), 'json'));
  947.             } catch (\Exception $e) {
  948.                 $this->entityManager->remove($OrderAddress);
  949.                 $this->entityManager->remove($shippingAddress);
  950.                 return new Response($this->serializer->serialize($this->errorResponseBlob('There was a problem getting the billing in INTERNAL SERVER' $e), 'json'));
  951.             }
  952.         } else {
  953.             return new Response($this->serializer->serialize($this->errorResponseBlob('Invalid parameter'), 'json'));
  954.         }
  955.     }
  956.     /**
  957.      * @Route("out_of_app/api/order/create", name="create_out_of_app_order", methods={"POST"})
  958.      */
  959.     public function CreateOutOfAppOrder(Request $request)
  960.     {
  961.         $currentToken $this->get('security.token_storage')->getToken();
  962.         $userId $currentToken->getUser()->getId();
  963.         $data json_decode($request->getContent(), 'true');
  964.         if (isset($data['order_details']) && isset($data['order_address']) && isset($data['shipping_address'])) {
  965.             $order_address_id null;
  966.             $shipping_address_id null;
  967.             $existingAddress $this->entityManager->getRepository(Adresses::class)->findOneBy([
  968.                 'user_id' => $userId,
  969.                 'location' => $data['order_address']
  970.             ]);
  971.             if (!$existingAddress) {
  972.                 $OrderAddress = new Adresses();
  973.                 $OrderAddress->setDescription("this my description and its an order address");
  974.                 $OrderAddress->setName("no name yet");
  975.                 $OrderAddress->setPhoneNumber("92702550");
  976.                 $OrderAddress->setLocation($data['order_address']);
  977.                 $OrderAddress->setNear("near location");
  978.                 $OrderAddress->setQuartier("Nothing here");
  979.                 $OrderAddress->setDescriptionDetails("decription details of mine");
  980.                 $OrderAddress->setUserId($userId);
  981.                 $OrderAddress->setUpdatedAt(date("Y-m-d H:i:s"));
  982.                 $OrderAddress->setState(1);
  983.                 $this->entityManager->persist($OrderAddress);
  984.                 $this->entityManager->flush();
  985.                 $order_address_id $OrderAddress->getId();
  986.             } else {
  987.                 $order_address_id $existingAddress->getId();
  988.             }
  989.             $existingShippingAddress $this->entityManager->getRepository(Adresses::class)->findOneBy([
  990.                 'user_id' => $userId,
  991.                 'location' => $data['shipping_address']
  992.             ]);
  993.             if (!$existingShippingAddress) {
  994.                 $shippingAddress = new Adresses();
  995.                 $shippingAddress->setDescription("this my description and its a shipping address");
  996.                 $shippingAddress->setName("no name yet");
  997.                 $shippingAddress->setPhoneNumber("92702550");
  998.                 $shippingAddress->setLocation($data['shipping_address']);
  999.                 $shippingAddress->setNear("near location");
  1000.                 $shippingAddress->setQuartier("Nothing here");
  1001.                 $shippingAddress->setDescriptionDetails("decription details of mine");
  1002.                 $shippingAddress->setUserId($userId);
  1003.                 $shippingAddress->setUpdatedAt(date("Y-m-d H:i:s"));
  1004.                 $shippingAddress->setState(1);
  1005.                 $this->entityManager->persist($shippingAddress);
  1006.                 $this->entityManager->flush();
  1007.                 $shipping_address_id $shippingAddress->getId();
  1008.             } else {
  1009.                 $shipping_address_id $existingShippingAddress->getId();
  1010.             }
  1011.             try {
  1012.                 $jsonData json_encode([
  1013.                     "order_details" => $data['order_details'],
  1014.                     "order_address" => [$order_address_id],
  1015.                     "shipping_address" => $shipping_address_id,
  1016.                     "voucher_id" => null,
  1017.                     "order_type" => 3,
  1018.                     "transaction_password" => "1204",
  1019.                     "infos" => "",
  1020.                     "use_kaba_point" => false,
  1021.                     "pay_at_delivery" => true,
  1022.                     "companie_service_fee" => $data['service_fee'],
  1023.                     "phone_number" => $data['phone_number']
  1024.                 ]);
  1025.                 $createCommandRequest = new Request(
  1026.                     [],
  1027.                     [],
  1028.                     [],
  1029.                     [],
  1030.                     [],
  1031.                     [
  1032.                         'CONTENT_TYPE' => 'application/json'
  1033.                     ],
  1034.                     $jsonData
  1035.                 );
  1036.                 $createCommand $this->createOutOfAppOrderWithVoucherAction($createCommandRequest);
  1037.                 $Command $createCommand->getContent();
  1038.                 $CommandData json_decode($Commandtrue);
  1039.                 $order = new OutOfAppOrder();
  1040.                 $order->setCommandId($CommandData['data']['command_id']);
  1041.                 $order->setServiceFee($data['service_fee']);
  1042.                 $order->setAdditionnalImageLinks($data['additionnal_images_links'] ?? []);
  1043.                 $order->setShippingAddress($data['shipping_address']);
  1044.                 $order->setOrderAddress($data['order_address']);
  1045.                 $order->setAdditionnalInfo("Info  : \n" $data['additionnal_info'] . "\n" "Info pharmacie :  \n" $data['pharmacie_info']);
  1046.                 $order->setPhoneNumber($data['phone_number'] ?? null);
  1047.                 $order->setReceipt(null);
  1048.                 $this->entityManager->persist($order);
  1049.                 $this->entityManager->flush();
  1050.                 $res = [];
  1051.                 $res['distance'] = $CommandData['data']['distance'];
  1052.                 $res['shipping_pricing'] =  $CommandData['data']['shipping_pricing'];
  1053.                 $res['command_pricing'] = $CommandData['data']['command_pricing'];
  1054.                 $res['additional_fees'] = $CommandData['data']['additional_fees'];
  1055.                 $res['out_of_range'] = $CommandData['data']['out_of_range'];
  1056.                 $res['total_pricing'] = $CommandData['data']['total_pricing'];
  1057.                 $res['command_id'] = $CommandData['data']['command_id'];
  1058.                 $res['company_commission_fee'] = $data['service_fee'];
  1059.                 return  new Response($this->serializer->serialize($this->okResponseBlob($res), 'json'));
  1060.             } catch (\Exception $e) {
  1061.                 return new Response($this->serializer->serialize($this->errorResponseBlob('There was a problem getting the billing in INTERNAL SERVER' $e), 'json'));
  1062.             }
  1063.         } else {
  1064.             return new Response($this->serializer->serialize($this->errorResponseBlob('Invalid parameter'), 'json'));
  1065.         }
  1066.     }
  1067.     /**
  1068.      * @Route("out_of_app/api/order/details/get", name="out_of_app_order_details_get", methods={"POST"})
  1069.      */
  1070.     public function getOutOfAppOrderDetails(Request $request)
  1071.     {
  1072.         $currentToken $this->get('security.token_storage')->getToken();
  1073.         $id $currentToken->getUser()->getId();
  1074.         $json_data $request->getContent();
  1075.         $data json_decode($json_datatrue);
  1076.         $command_id $data["command_id"];
  1077.         $serviceFee 0;
  1078.         $out_of_app_order $this->entityManager->getRepository(OutOfAppOrder::class)->findOneBy(['commandId' => $command_id]);
  1079.         $serviceFee 0;
  1080.         if ($out_of_app_order) {
  1081.             $serviceFee $out_of_app_order->getServiceFee();
  1082.         }
  1083.         $command_detail_request = new Request(
  1084.             [],
  1085.             [],
  1086.             [],
  1087.             [],
  1088.             [],
  1089.             [
  1090.                 'CONTENT_TYPE' => 'application/json'
  1091.             ],
  1092.             json_encode([
  1093.                 'command_id' => $command_id,
  1094.                 "companie_service_fee" => $serviceFee
  1095.             ])
  1096.         );
  1097.         $command_detail $this->getOutOfAppOrderDetailsWithVoucher($command_detail_request);
  1098.         $command $command_detail->getContent();
  1099.         $commandData json_decode($commandtrue);
  1100.         $res = [];
  1101.         $out_of_app_order $this->entityManager->getRepository(OutOfAppOrder::class)->findOneBy(['commandId' => $commandData['data']['command']['id']]);
  1102.         $res['id'] = $commandData['data']['command']['id'];
  1103.         $res['food_list'] = $commandData['data']['command']['food_list'];
  1104.         $res['food_pricing'] = $commandData['data']['command']['food_pricing'];
  1105.         $res['shipping_pricing'] =  $commandData['data']['command']['shipping_pricing'];
  1106.         $res['out_of_range'] = $commandData['data']['command']['out_of_range'];
  1107.         $res['additional_fees'] = $commandData['data']['command']['additionnal_fee'];
  1108.         $res['company_commission_fee'] = $commandData['data']['command']['serviceFee'];;
  1109.         $res['total_pricing'] = $commandData['data']['command']['total_pricing'];
  1110.         $res['shipping_address'] = $commandData['data']['command']['shipping_address']['location'];
  1111.         $res['delivery_time_estimation_in_mins'] = "30";
  1112.         $res['last_update'] = $commandData['data']['command']['last_update'];
  1113.         $res['start_time'] = $commandData['data']['command']['start_time'];
  1114.         $res['start_date'] = $commandData['data']['command']['start_date'];
  1115.         $res['state'] = $commandData['data']['command']['state'];
  1116.         $res['delivery_time_estimation_in_mins'] = "30";
  1117.         $res['receipt_image'] = $out_of_app_order->getReceipt();
  1118.         $res['additionnal_info'] = $out_of_app_order->getAdditionnalInfo();
  1119.         $res['phone_numnber'] = $out_of_app_order->getPhoneNumber();
  1120.         return new Response($this->serializer->serialize($this->okResponseBlob($res), 'json'), 200);
  1121.     }
  1122.     /**
  1123.      * @Route("api/token/generate", name="api_token_generate", methods={"POST"})
  1124.      */
  1125.     public function generateJwt(Request $request): JsonResponse
  1126.     {
  1127.         $data  json_decode($request->getContent(), true);
  1128.         $client $this->entityManager->getRepository(Client::class)->findOneBy(['username' => $data['username']]);
  1129.         if ($client) {
  1130.             $privateKeyPath $this->getParameter('kernel.project_dir') . '/config/jwt/private.pem';
  1131.             $privateKey file_get_contents($privateKeyPath);
  1132.             $payload = [
  1133.                 'roles'    => ['ROLE_USER'],
  1134.                 'username' => $data['username'],
  1135.                 'iat'      => time(),
  1136.                 'exp'      => time() + (10 365 24 60 60)
  1137.             ];
  1138.             $jwt JWT::encode($payload$privateKey'RS256');
  1139.             return new JsonResponse(['token' => $jwt]);
  1140.         } else {
  1141.             return new JsonResponse(['Error' => "User doesnt exists"]);
  1142.         }
  1143.     }
  1144.     /**
  1145.      * @Route("mobile/api/v4/livreur/out_of_app_order/update", name="update_out_of_app_order", methods={"POST"})
  1146.      */
  1147.     public function UpdateOutOfAppOrder(Request $request)
  1148.     {
  1149.         $currentToken $this->get('security.token_storage')->getToken();
  1150.         $data json_decode($request->getContent(), 'true');
  1151.         $command_id $data['command_id'];
  1152.         $res = [];
  1153.         $command =  $this->entityManager->getRepository(Command::class)->find($command_id);
  1154.         //change me depending on env.
  1155.         $endPoint "http://app.kaba-delivery.com/livreur/api/command/modify";
  1156.         $content = [
  1157.             'headers' => [
  1158.                 'Authorization' => 'Bearer ' $currentToken->getCredentials(),
  1159.                 'Accept' => 'application/json',
  1160.                 'Cache-Control' => 'no-cache',
  1161.             ],
  1162.             'json' => [
  1163.                 'command_id' => $command_id,
  1164.             ],
  1165.         ];
  1166.         if (isset($data['order_address'])) {
  1167.             $names array_map(function ($product) {
  1168.                 return $product['name'];
  1169.             }, $data['temp_product']);
  1170.             $result implode(","$names);
  1171.             //check if its an update on order address
  1172.             if ($data['order_address'] != null) {
  1173.                 $client $this->entityManager->getRepository(Client::class)->find($command->getClientId());
  1174.                 $order_address_entity = new Adresses();
  1175.                 $order_address_entity->setDescription("Achat pour le produit " $result);
  1176.                 $order_address_entity->setName("Achat pour le produit" $data['temp_product'][0]['name']);
  1177.                 $order_address_entity->setPhoneNumber($client->getUsername());
  1178.                 $order_address_entity->setLocation($data['order_address']);
  1179.                 $order_address_entity->setNear("azertyuiop");
  1180.                 $order_address_entity->setQuartier("Aucun");
  1181.                 $order_address_entity->setDescriptionDetails("Achat pour le produit " $result);
  1182.                 $order_address_entity->setUserId($command->getClientId());
  1183.                 $order_address_entity->setUpdatedAt(date("Y-m-d H:i:s"));
  1184.                 $order_address_entity->setState(1);
  1185.                 $order_address_entity->setLocation($data['order_address']);
  1186.                 $address_to_delete $this->entityManager->getRepository(Adresses::class)->findOneBy(['name' => "Achat pour le produit " $data['temp_product'][0]['name']]);
  1187.                 if ($address_to_delete) {
  1188.                     $this->entityManager->remove($address_to_delete);
  1189.                 }
  1190.                 $this->entityManager->persist($order_address_entity);
  1191.                 $this->entityManager->flush();
  1192.                 $client_id $command->getClientId();
  1193.                 $voucher_usage $this->entityManager->getRepository(VoucherUsage::class)->findOneBy([
  1194.                     'commandId' => $command_id,
  1195.                     'userId' => $client_id
  1196.                 ]);
  1197.                 $jsonData json_encode([
  1198.                     "order_details" => $data['temp_product'],
  1199.                     "order_address" => [$order_address_entity->getId()],
  1200.                     "shipping_address" => $command->getShippingAddress()["id"],
  1201.                     "voucher_id" => $voucher_usage $voucher_usage->getVoucherId() : null,
  1202.                     "use_kaba_point" => false,
  1203.                     "pay_at_delivery" => true,
  1204.                     "user_id" => $client_id
  1205.                 ]);
  1206.                 $billingRequest = new Request(
  1207.                     [],
  1208.                     [],
  1209.                     [],
  1210.                     [],
  1211.                     [],
  1212.                     [
  1213.                         'CONTENT_TYPE' => 'application/json',
  1214.                     ],
  1215.                     $jsonData
  1216.                 );
  1217.                 $user $this->entityManager->getRepository(Client::class)->find($client_id);
  1218.                 $type filter_var($user->getUsername(), FILTER_VALIDATE_EMAIL) ? 1;
  1219.                 $getBilling $this->getOutOfAppOrderBilling($billingRequest);
  1220.                 $getBillingContent $getBilling->getContent();
  1221.                 $getBillingData json_decode($getBillingContenttrue);
  1222.                 $order_address_array $this->getAdress($order_address_entity->getId());
  1223.                 
  1224.                 $res['distance'] = $getBillingData['data']['distance'];
  1225.                 $res['shipping_pricing'] = $getBillingData['data']['shipping_pricing'];
  1226.                 $res['command_pricing'] = $getBillingData['data']['command_pricing'];
  1227.                 $res['additional_fees'] = $getBillingData['data']['additional_fees_total_price'];
  1228.                 $res['out_of_range'] = $getBillingData['data']['out_of_range'];
  1229.                 $res['total_pricing'] = $getBillingData['data']['total_pricing'];
  1230.                 $standard_price $this->shippingPricing($order_address_entity->getId(), $command->getShippingAddress()["id"], $type);
  1231.                 $without_promotion_billing_for_email $standard_price["email_account_billing"];
  1232.                 $extra_shipping_pricing intval($standard_price["email_account_billing"]) - intval($getBillingData['data']['reduced_shipping_price']);
  1233.                 $command->setLastUpdate(date("Y-m-d H:i:s"));
  1234.                 $command->setShippingPricing(strval($getBillingData['data']['reduced_shipping_price']));
  1235.                 $command->setEmailAccountShippingPricing(strval($without_promotion_billing_for_email));
  1236.                 $command->setPhoneNumberAccountShippingPricing(strval($getBillingData['data']['reduced_shipping_price']));
  1237.                 $command->setExtraShippingPricing(strval($extra_shipping_pricing));
  1238.                 $command->setBaseShippingPricing(strval($standard_price["billing"])); 
  1239.                 $command->setOrderShippingAddress($order_address_array);
  1240.                 $this->entityManager->persist($command);
  1241.                 $this->entityManager->flush();
  1242.             }
  1243.         }
  1244.         if (isset($data['foods'])) {
  1245.             //check if its an update on food price
  1246.             if ($data['foods'] != null) {
  1247.                 $food_list = [];
  1248.                 $order_details = [];
  1249.                 $normalizer = new Serializer([new ObjectNormalizer()]);
  1250.                 foreach ($data['foods'] as $food) {
  1251.                     $food_item $this->entityManager->getRepository(Food::class)->find($food['id']);
  1252.                     $food_item->setPrice($food['price']);
  1253.                     $this->entityManager->persist($food_item);
  1254.                     $food_command $command->getFoodCommand();
  1255.                     $food_shipping null;
  1256.                     foreach ($food_command as $fc) {
  1257.                         if ($fc['food_id'] == $food_item->getId()) {
  1258.                             $food_shipping $fc['food_shipping'];
  1259.                             break;
  1260.                         }
  1261.                     }
  1262.                     array_push($food_list, [
  1263.                         'food_id' => $food_item->getId(),
  1264.                         'quantity' => $food['quantity'],
  1265.                         'food_entity' => $normalizer->normalize($food_item),
  1266.                         'food_shipping' => $food_shipping
  1267.                     ]);
  1268.                     array_push($order_details, [
  1269.                         "name" => $food_item->getName(),
  1270.                         "image" => $food_item->getPic(),
  1271.                         "price" => $food_item->getPrice(),
  1272.                         "quantity" => $food['quantity']
  1273.                     ]);
  1274.                 }
  1275.                 $command->setFoodCommand($food_list);
  1276.                 $command->setOrderDetails($order_details);
  1277.                 $this->entityManager->persist($command);
  1278.                 $this->entityManager->flush();
  1279.             }
  1280.         }
  1281.         $response $this->http_client->request('POST'$endPoint$content);
  1282.         return new JsonResponse($res);
  1283.     }
  1284.     /**
  1285.      * @Route("mobile/api/v4/livreur/order_receipt/update", name="update_order_receipt", methods={"POST"})
  1286.      */
  1287.     public function updateOrderReceipt(Request $request)
  1288.     {
  1289.         $data json_decode($request->getContent(), true);
  1290.         $command_id $data['command_id'];
  1291.         $receipt $data['image_link'];
  1292.         $out_of_app_order $this->entityManager->getRepository(OutOfAppOrder::class)->findOneBy(['commandId' => $command_id]);
  1293.         $out_of_app_order->setReceipt($receipt);
  1294.         $this->entityManager->persist($out_of_app_order);
  1295.         $this->entityManager->flush();
  1296.         return new JsonResponse(['message' => 'Receipt updated successfully']);
  1297.     }
  1298.     /**
  1299.      * @Route("mobile/api/v4/livreur/command/additionnal_images/get", name="get_command_additionnal_images", methods={"POST"})
  1300.      */
  1301.     public function getCommandAdditionnalImages(Request $request)
  1302.     {
  1303.         $data json_decode($request->getContent(), true);
  1304.         $command_id $data['command_id'];
  1305.         $images = [];
  1306.         $out_of_app_order $this->entityManager->getRepository(OutOfAppOrder::class)->findOneBy(['commandId' => $command_id]);
  1307.         if ($out_of_app_order) {
  1308.             $images $out_of_app_order->getAdditionnalImageLinks();
  1309.             foreach ($images as $image) {
  1310.                 array_push($images$image);
  1311.             }
  1312.             return new JsonResponse(['images' => $images]);
  1313.         } else {
  1314.             return new JsonResponse(['images' => []]);
  1315.         }
  1316.     }
  1317.     public function setDefaultOrderAddress($shipping_address$currentToken)
  1318.     {
  1319.         $order_address_id null;
  1320.         $batchSize 100;
  1321.         $offset 0;
  1322.     
  1323.         do {
  1324.             $addresses $this->entityManager->createQueryBuilder()
  1325.                 ->select('a.location, a.id')
  1326.                 ->from(Adresses::class, 'a')
  1327.                 ->setFirstResult($offset)
  1328.                 ->setMaxResults($batchSize)
  1329.                 ->getQuery()
  1330.                 ->getArrayResult();
  1331.     
  1332.             foreach ($addresses as $address) {
  1333.                 $distance  $this->getDistance($shipping_address->getLocation(), $address['location']);
  1334.                 if ($distance <= 1000) {
  1335.                     return $address['id'];
  1336.                 }
  1337.             }
  1338.     
  1339.             $offset += $batchSize;
  1340.         } while (count($addresses) === $batchSize);
  1341.     
  1342.         return null;
  1343.     }
  1344.     public function createPaymentBill($data$command_id)
  1345.     {
  1346.         $command $this->entityManager->getRepository(Command::class)->find($command_id);
  1347.         $payment_bill = new PaymentBill();
  1348.         $payment_bill
  1349.             ->setShippingPricing(isset($data["shipping_pricing"]) ? $data["shipping_pricing"] : -1)
  1350.             ->setPromotionShippingPricing(isset($data["promotion_shipping_pricing"]) ? $data["promotion_shipping_pricing"] : -1)
  1351.             ->setPromotionPricing(isset($data["promotion_pricing"]) ? $data["promotion_pricing"] : -1)
  1352.             ->setCommandPricing(isset($data["command_pricing"]) ? $data["command_pricing"] : -1)
  1353.             ->setRemise(isset($data["remise"]) ? $data["remise"] : -1)
  1354.             ->setTotalPricing(isset($data["total_pricing"]) ? $data["total_pricing"] : -1)
  1355.             ->setTotalNormalPricing(isset($data["total_normal_pricing"]) ? $data["total_normal_pricing"] : -1)
  1356.             ->setAccountBalance(isset($data["account_balance"]) ? $data["account_balance"] : -1)
  1357.             ->setOutOfRange(isset($data["out_of_range"]) ? $data["out_of_range"] : false)
  1358.             ->setPayAtDelivery(isset($data["pay_at_delivery"]) ? $data["pay_at_delivery"] : false)
  1359.             ->setPrepaid(isset($data["prepayed"]) ? $data["prepayed"] : false)
  1360.             ->setTrustful(isset($data["trustful"]) ? $data["trustful"] : -1)
  1361.             ->setMaxPay(isset($data["max_pay"]) ? $data["max_pay"] : -1)
  1362.             ->setCookingTime(isset($data["cooking_time"]) ? $data["cooking_time"] : -1)
  1363.             ->setCanPreorder(isset($data["can_preorder"]) ? $data["can_preorder"] : -1)
  1364.             ->setDiscount(isset($data["discount"]) ? $data["discount"] : "")
  1365.             ->setOpenType(isset($data["open_type"]) ? $data["open_type"] : -1)
  1366.             ->setWorkingHour(isset($data["working_hour"]) ? $data["working_hour"] : "")
  1367.             ->setReason(isset($data["reason"]) ? $data["reason"] : "")
  1368.             ->setDeliveryFrames(isset($data["delivery_frames"]) && is_array($data["delivery_frames"]) ? $data["delivery_frames"] : null)
  1369.             ->setBillBuilt(isset($data["is_bill_built"]) ? $data["is_bill_built"] : false)
  1370.             ->setCheckedOpen(isset($data["checked_open"]) ? $data["checked_open"] : false)
  1371.             ->setTotalPreorderPricing(isset($data["total_preorder_pricing"]) ? $data["total_preorder_pricing"] : -1)
  1372.             ->setKabaPoint(isset($data["kaba_point"]) ? $data["kaba_point"] : ["value" => null])
  1373.             ->setEligibleVouchers(isset($data["eligible_vouchers"]) ? $data["eligible_vouchers"] : ["value" => null])
  1374.             ->setAdditionalFees(isset($data["additional_fees"]) ? $data["additional_fees"] : ["value" => null])
  1375.             ->setAdditionalFeesTotalPrice(isset($data["additional_fees_total_price"]) ? $data["additional_fees_total_price"] : -1)
  1376.             ->setCommandId($command);
  1377.         $this->entityManager->persist($payment_bill);
  1378.         $this->entityManager->flush();
  1379.         return new Response("Success"200);
  1380.     }
  1381.     private function applyFirstCommandProccess($id$commandId$foodPring$shippingPrincing)
  1382.     {
  1383.         $loyalty $this->entityManager->getRepository(Loyalty::class)->findOneBy([
  1384.             "status" => "1"
  1385.         ]);
  1386.         $user =  $this->entityManager->getRepository(Client::class)->find($id);
  1387.         $today = new \DateTime();
  1388.         $userCreatedAt $user->getCreatedAt();
  1389.         $bonus = new PayBonus();
  1390.         $bonus->setCreatedAt($today)
  1391.             ->setClientId($id)
  1392.             ->setCommandDate($today)
  1393.             ->setPayDate($today)
  1394.             ->setPhone($user->getUsername())
  1395.             ->setAccountDate($user->getCreatedAt() ? new \DateTime("@$userCreatedAt") : $today)
  1396.             ->setCommandId($commandId)
  1397.             ->setOfferType($loyalty->getType())
  1398.             ->setStatus('-1')
  1399.             ->setFoodPrice($foodPring)
  1400.             ->setShippingPrice($shippingPrincing)
  1401.             ->setAmount($loyalty->getType() == '1' $shippingPrincing $loyalty->getAmount());
  1402.         $em $this->entityManager;
  1403.         $em->persist($bonus);
  1404.         $em->flush();
  1405.     }
  1406.     public function shippingPricing($order_address$shipping_address$type 1)
  1407.     {
  1408.         $orderAdress =  $this->entityManager->getRepository(Adresses::class)->find($order_address);
  1409.         $shippingAddress =  $this->entityManager->getRepository(Adresses::class)->find($shipping_address);
  1410.         $response $this->getDistance($orderAdress->getLocation(), $shippingAddress->getLocation());
  1411.         $distance $response;
  1412.         $billing 0;
  1413.         $emailAccountBilling 0;
  1414.         $phoneNumberAccountBilling 0;
  1415.         $out_of_range false;
  1416.         $db_billing $type == $this->entityManager->getRepository(Billing2::class)->findAll() : $this->entityManager->getRepository(Billing::class)->findAll();
  1417.         $db_phoneNumber_billing $this->entityManager->getRepository(Billing::class)->findAll();
  1418.         $db_email_account_billing $this->entityManager->getRepository(Billing2::class)->findAll();
  1419.         if ($db_billing != null) {
  1420.             foreach ($db_billing as $db_billing_item) {
  1421.                 if ($distance >= intval($db_billing_item->getRangeStart()) * 1000 && $distance intval($db_billing_item->getRangeEnd()) * 1000) {
  1422.                     $billing $db_billing_item->getValue();
  1423.                 }
  1424.             }
  1425.         }
  1426.         if ($db_phoneNumber_billing != null) {
  1427.             foreach ($db_phoneNumber_billing as $item) {
  1428.                 if ($distance >= intval($item->getRangeStart()) * 1000 && $distance intval($item->getRangeEnd()) * 1000) {
  1429.                     $phoneNumberAccountBilling $item->getValue();
  1430.                 }
  1431.             }
  1432.         }
  1433.         if ($db_email_account_billing != null) {
  1434.             foreach ($db_email_account_billing as $item) {
  1435.                 if ($distance >= intval($item->getRangeStart()) * 1000 && $distance intval($item->getRangeEnd()) * 1000) {
  1436.                     $emailAccountBilling $item->getValue();
  1437.                 }
  1438.             }
  1439.         }
  1440.         if ($billing == 0) {
  1441.             $out_of_range true;
  1442.         }
  1443.         return [
  1444.             'billing' => $billing,
  1445.             'email_account_billing' => $emailAccountBilling,
  1446.             'phoneNumber_account_billing' => $phoneNumberAccountBilling,
  1447.             'out_of_range' => $out_of_range,
  1448.             'distance' => $distance
  1449.         ];
  1450.     }
  1451.     private function calculate_shipping_price($distance$currentToken)
  1452.     {
  1453.         if (is_string($currentToken)) {
  1454.             $jwtData json_decode(base64_decode(explode('.'$currentToken)[1]), true);
  1455.             $username $jwtData['username'];
  1456.             $type filter_var($usernameFILTER_VALIDATE_EMAIL) ? 1;
  1457.         } else {
  1458.             $type filter_var($currentToken->getUsername(), FILTER_VALIDATE_EMAIL) ? 1;
  1459.         }
  1460.         $shipping_price 0;
  1461.         $billing 0;
  1462.         $db_billing $type == ?  $this->entityManager->getRepository(Billing2::class)->findAll() :  $this->entityManager->getRepository(Billing::class)->findAll();
  1463.         if ($db_billing != null) {
  1464.             foreach ($db_billing as $db_billing_item) {
  1465.                 if ($distance >= intval($db_billing_item->getRangeStart()) * 1000 && $distance intval($db_billing_item->getRangeEnd()) * 1000) {
  1466.                     $billing $db_billing_item->getValue();
  1467.                 }
  1468.             }
  1469.         }
  1470.         $shipping_price intval($billing);
  1471.         return $shipping_price;
  1472.     }
  1473.     private function configsWithVoucher($data$currentToken$user$order_address$shipping_address)
  1474.     {
  1475.         $distance $this->getDistance($order_address->getLocation(), $shipping_address->getLocation());
  1476.         $voucher_billing 0;
  1477.         $is_voucher_on_billing false;
  1478.         $is_voucher_on_billing_already_applyed false;
  1479.         $check_voucher_valid $this->checkIfVoucherValid($user->getId(), $data["voucher_id"]);
  1480.         $type 1;
  1481.         if (is_string($currentToken)) {
  1482.             $jwtData json_decode(base64_decode(explode('.'$currentToken)[1]), true);
  1483.             $username $jwtData['username'];
  1484.             $type filter_var($usernameFILTER_VALIDATE_EMAIL) ? 1;
  1485.         } else {
  1486.             $type filter_var($currentToken->getUsername(), FILTER_VALIDATE_EMAIL) ? 1;
  1487.         }
  1488.         $db_billing $type == ?  $this->entityManager->getRepository(Billing2::class)->findAll() :  $this->entityManager->getRepository(Billing::class)->findAll();
  1489.         if ($db_billing != null) {
  1490.             foreach ($db_billing as $db_billing_item) {
  1491.                 if (
  1492.                     $distance >= intval($db_billing_item->getRangeStart()) * 1000 &&
  1493.                     $distance intval($db_billing_item->getRangeEnd()) * 1000
  1494.                 ) {
  1495.                     $billing $db_billing_item->getValue();
  1496.                     $voucher_billing intval($billing);
  1497.                     if ($check_voucher_valid["valid"] == true) {
  1498.                         $is_voucher_on_billing true;
  1499.                         break;
  1500.                     }
  1501.                 }
  1502.             }
  1503.         }
  1504.         if ($check_voucher_valid["valid"] == true) {
  1505.             // check if reduction on billing
  1506.             if ($check_voucher_valid["type"] == 2) {
  1507.                 if ($is_voucher_on_billing) {
  1508.                     if ($check_voucher_valid["category"] == 1) {
  1509.                         //in percent
  1510.                         $reductions = ($voucher_billing $check_voucher_valid["value"]) / 100;
  1511.                         $voucher_billing -= $reductions;
  1512.                         $is_voucher_on_billing_already_applyed true;
  1513.                     } else {
  1514.                         //cash
  1515.                         $voucher_billing -= $check_voucher_valid["value"];
  1516.                         $is_voucher_on_billing_already_applyed true;
  1517.                     }
  1518.                 }
  1519.             }
  1520.         }
  1521.         $configs_with_voucher = [];
  1522.         $configs_with_voucher["voucher_billing"] = $voucher_billing;
  1523.         $configs_with_voucher["is_voucher_on_billing"] = $is_voucher_on_billing;
  1524.         $configs_with_voucher["is_voucher_on_billing_already_applyed"] = $is_voucher_on_billing_already_applyed;
  1525.         $configs_with_voucher["check_voucher_valid"] = $check_voucher_valid;
  1526.         return $configs_with_voucher;
  1527.     }
  1528.     private function get_kaba_point($client_id$shipping_price)
  1529.     {
  1530.         $kabaPoint $this->getMiniKabaPointBalance($client_id$shipping_price);
  1531.         return $kabaPoint;
  1532.     }
  1533.     private function getOutOfAppAdditionnalFees($shipping_price$shipping_address$order_address)
  1534.     {
  1535.         $weather_fee 0;
  1536.         $night_fee 0;
  1537.         $week_end_fee 0;
  1538.         $holy_day_fee 0;
  1539.         $kaba_fee 0;
  1540.         //ADD WEATHER_FEE 
  1541.         $raining_in_order_zone false;
  1542.         $raining_in_customer_zone false;
  1543.         $zones =  $this->entityManager->getRepository(Zone::class)->findAll();
  1544.         //check if order's zone
  1545.         $order_zone null;
  1546.         foreach ($zones as $zone) {
  1547.             list($orderLat$OrderLng) = explode(':'$order_address->getLocation());
  1548.             $location json_decode($zone->getLocation(), true);
  1549.             $latitude $location['lat'];
  1550.             $longitude $location['lng'];
  1551.             $distance $this->haversineDistance(
  1552.                 (float)$orderLat,
  1553.                 (float)$OrderLng,
  1554.                 $latitude,
  1555.                 $longitude
  1556.             );
  1557.             if ($distance <= $zone->getRadius()) {
  1558.                 $order_zone $zone;
  1559.                 break;
  1560.             }
  1561.         }
  1562.         if ($order_zone) {
  1563.             $weather_rule $this->entityManager->getRepository(WeatherRule::class)->findOneBy(['zone_id' => $order_zone->getId()]);
  1564.             if ($weather_rule) {
  1565.                 $current_time = new DateTime();
  1566.                 $time_end $weather_rule->getTimeEnd();
  1567.                 $time_start $weather_rule->getTimeStart();
  1568.                 if ($current_time->format('H:i') >= $time_start->format('H:i') && $current_time->format('H:i') <= $time_end->format('H:i'))
  1569.                     $raining_in_order_zone $weather_rule->isEnabled();
  1570.                 if ($current_time->format('H:i') > $time_end->format('H:i')) {
  1571.                     $raining_in_order_zone false;
  1572.                     $weather_rule->setEnabled(false);
  1573.                     $this->entityManager->persist($weather_rule);
  1574.                     $this->entityManager->flush();
  1575.                 }
  1576.             } 
  1577.         } 
  1578.         //check shipping zone 
  1579.         $customer_zone null;
  1580.         foreach ($zones as $zone) {
  1581.             list($clientLat$clientLng) = explode(':'$shipping_address->getLocation());
  1582.             $location json_decode($zone->getLocation(), true);
  1583.             $latitude $location['lat'];
  1584.             $longitude $location['lng'];
  1585.             $distance $this->haversineDistance(
  1586.                 (float)$clientLat,
  1587.                 (float)$clientLng,
  1588.                 $latitude,
  1589.                 $longitude
  1590.             );
  1591.             if ($distance <= $zone->getRadius()) {
  1592.                 $customer_zone $zone;
  1593.                 break;
  1594.             }
  1595.         }
  1596.         if ($customer_zone) {
  1597.             $weatherRuleForClientZone $this->entityManager->getRepository(WeatherRule::class)->findOneBy(['zone_id' => $customer_zone->getId()]);
  1598.             $raining_in_customer_zone $weatherRuleForClientZone->isEnabled();
  1599.             if ($raining_in_customer_zone == true || $raining_in_order_zone == true) {
  1600.                 $weather_additional_fee $this->entityManager->getRepository(AdditionalFees::class)->findByFeeType(AdditionnalFeeType::WEATHER_FEE);
  1601.                 if ($weather_additional_fee->getAmountType() == AdditionnalFeeAmountType::PRIX_FIX) {
  1602.                     $weather_fee $weather_additional_fee->getAmountValue();
  1603.                 } else {
  1604.                     $weather_fee = ($shipping_price  * ($weather_additional_fee->getAmountValue() / 100));
  1605.                 }
  1606.             }
  1607.         }
  1608.         //ADD NIGHT_FEE 
  1609.         $current_time = new DateTime();
  1610.         $night_additional_fee $this->entityManager->getRepository(AdditionalFees::class)->findByFeeType(AdditionnalFeeType::NIGHT_FEE);
  1611.         $night_rule $this->entityManager->getRepository(AdditionalFeeRule::class)->findOneby(['rule_type' => AdditionalFeeRuleType::TIME_FRAME]);
  1612.         $night_time_start $night_rule->getTimeStart();
  1613.         $night_time_end $night_rule->getTimeEnd();
  1614.         if ($current_time->format('H:i') >= $night_time_start->format('H:i') && $current_time->format('H:i') < $night_time_end->format('H:i')) {
  1615.             if ($night_additional_fee->isEnabled()) {
  1616.                 if ($night_additional_fee->getAmountType() == AdditionnalFeeAmountType::PRIX_FIX) {
  1617.                     $night_fee $night_additional_fee->getAmountValue();
  1618.                 } else {
  1619.                     $night_fee = ($shipping_price  * ($night_additional_fee->getAmountValue() / 100));
  1620.                 }
  1621.             }
  1622.         }
  1623.         //ADD WEEK_END FEE and HOLYDAY FEE
  1624.         $week_end_additional_fee $this->entityManager->getRepository(AdditionalFees::class)->findByFeeType(AdditionnalFeeType::NIGHT_FEE);
  1625.         $public_holyday_additional_fee $this->entityManager->getRepository(AdditionalFees::class)->findByFeeType(AdditionnalFeeType::PUBLIC_HOLYDAY_FEE);
  1626.         $free_day_rule $this->entityManager->getRepository(AdditionalFeeRule::class)->findOneby(['rule_type' => AdditionalFeeRuleType::FREE_DAY_FRAME]);
  1627.         $free_day_time_start $free_day_rule->getTimeStart();
  1628.         $free_day_time_end $free_day_rule->getTimeEnd();
  1629.         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')) {
  1630.             if ($week_end_additional_fee->isEnabled() && ($current_time->format('N') == || $current_time->format('N') == 7)) {
  1631.                 if ($week_end_additional_fee->getAmountType() == AdditionnalFeeAmountType::PRIX_FIX) {
  1632.                     $week_end_fee $week_end_additional_fee->getAmountValue();
  1633.                 } else {
  1634.                     $week_end_fee = ($shipping_price  * ($week_end_additional_fee->getAmountValue() / 100));
  1635.                 }
  1636.             }
  1637.             if ($public_holyday_additional_fee->isEnabled()) {
  1638.                 if ($public_holyday_additional_fee->getAmountType() == AdditionnalFeeAmountType::PRIX_FIX) {
  1639.                     $holy_day_fee $public_holyday_additional_fee->getAmountValue();
  1640.                 } else {
  1641.                     $holy_day_fee = ($shipping_price  * ($public_holyday_additional_fee->getAmountValue() / 100));
  1642.                 }
  1643.             }
  1644.         }
  1645.         //ADD KABA FEE 
  1646.         $kaba_commission_fee $this->entityManager->getRepository(AdditionalFees::class)->findOneBy(['fee_type' => AdditionnalFeeType::OUT_OF_APP_FEE]);
  1647.         if ($kaba_commission_fee->isEnabled()) {
  1648.             if ($kaba_commission_fee->getAmountType() == AdditionnalFeeAmountType::PRIX_FIX) {
  1649.                 $kaba_fee $kaba_commission_fee->getAmountValue();
  1650.             } else {
  1651.                 $kaba_fee = ($shipping_price  * ($kaba_commission_fee->getAmountValue() / 100));
  1652.             }
  1653.         }
  1654.         $fees = [$weather_fee$night_fee$week_end_fee$holy_day_fee,$kaba_fee];
  1655.         $count 0;
  1656.         foreach ($fees as $fee) {
  1657.             if ($fee 0) {
  1658.                 $count++;
  1659.             }
  1660.         }
  1661.         if ($count 3) {
  1662.             $weather_additional_fee $this->entityManager->getRepository(AdditionalFees::class)->findOneBy(["fee_type" => AdditionnalFeeType::WEATHER_FEE]);
  1663.             $night_additional_fee $this->entityManager->getRepository(AdditionalFees::class)->findOneBy(["fee_type" => AdditionnalFeeType::NIGHT_FEE]);
  1664.             $week_end_additional_fee $this->entityManager->getRepository(AdditionalFees::class)->findOneBy(["fee_type" => AdditionnalFeeType::WEEKEND_FEE]);
  1665.             $public_holiday_additional_fee $this->entityManager->getRepository(AdditionalFees::class)->findOneBy(["fee_type" => AdditionnalFeeType::PUBLIC_HOLYDAY_FEE]);
  1666.             $kaba_commission_fee $this->entityManager->getRepository(AdditionalFees::class)->findOneBy(['fee_type' => AdditionnalFeeType::OUT_OF_APP_FEE]);
  1667.        
  1668.             $fees_entities = [$weather_additional_fee$night_additional_fee$week_end_additional_fee$public_holiday_additional_fee,$kaba_commission_fee];
  1669.             usort($fees_entities, function ($a$b) {
  1670.                 return $a->getPriority() - $b->getPriority();
  1671.             });
  1672.             $top_two_entities array_slice($fees_entities03);
  1673.             $selected_fee_types = [];
  1674.             foreach ($top_two_entities as $entity) {
  1675.                 $selected_fee_types[] = $entity->getFeeType();
  1676.             }
  1677.             if (!in_array(AdditionnalFeeType::WEATHER_FEE$selected_fee_types)) {
  1678.                 $weather_fee 0;
  1679.             }
  1680.             if (!in_array(AdditionnalFeeType::NIGHT_FEE$selected_fee_types)) {
  1681.                 $night_fee 0;
  1682.             }
  1683.             if (!in_array(AdditionnalFeeType::WEEKEND_FEE$selected_fee_types)) {
  1684.                 $week_end_fee 0;
  1685.             }
  1686.             if (!in_array(AdditionnalFeeType::PUBLIC_HOLYDAY_FEE$selected_fee_types)) {
  1687.                 $holy_day_fee 0;
  1688.             }
  1689.             if (!in_array(AdditionnalFeeType::OUT_OF_APP_FEE$selected_fee_types)) {
  1690.                 $kaba_fee 0;
  1691.             }
  1692.         }
  1693.         $res = [];
  1694.         $res["WEATHER_FEE"] = $weather_fee;
  1695.         $res["NIGHT_FEE"] = $night_fee;
  1696.         $res["PUBLIC_HOLYDAY_FEE"] = $holy_day_fee;
  1697.         $res["WEEKEND_FEE"] = $week_end_fee;
  1698.         $res["OUT_OF_APP_FEE"] = $kaba_fee;
  1699.         return $res;
  1700.     }
  1701.     public function getAdditionalFeesTotalPricing($additional_fees)
  1702.     {
  1703.         $total_additional_fees_pricing 0;
  1704.         foreach ($additional_fees as $additional_fee) {
  1705.             $total_additional_fees_pricing += $additional_fee;
  1706.         }
  1707.         return $total_additional_fees_pricing;
  1708.     }
  1709.     private function haversineDistance($lat1$lng1$lat2$lng2): float
  1710.     {
  1711.         $earthRadius 6371;
  1712.         $lat1 deg2rad($lat1);
  1713.         $lng1 deg2rad($lng1);
  1714.         $lat2 deg2rad($lat2);
  1715.         $lng2 deg2rad($lng2);
  1716.         $dlat $lat2 $lat1;
  1717.         $dlng $lng2 $lng1;
  1718.         $a sin($dlat 2) ** cos($lat1) * cos($lat2) * sin($dlng 2) ** 2;
  1719.         $c atan2(sqrt($a), sqrt($a));
  1720.         return $earthRadius $c 1000;
  1721.     }
  1722.     private function get_total_pricing($res$configs_with_voucher$data$kabaPoint$command_pricing)
  1723.     {
  1724.         $total_pricing 0;
  1725.         $total_pricing $res['shipping_pricing'];
  1726.         if (isset($data["voucher_id"]) && $data["voucher_id"] != null) {
  1727.             $voucher_billing intval($configs_with_voucher["voucher_billing"]) < $configs_with_voucher["voucher_billing"];
  1728.             $total_pricing intval($voucher_billing);
  1729.         }
  1730.         if (isset($data['use_kaba_point']) && $data['use_kaba_point']) {
  1731.             $amount intval($kabaPoint["amount_to_reduce"]);
  1732.             $total_pricing $res["shipping_pricing"] - $amount;
  1733.         }
  1734.         $type = [];
  1735.         $type["total_pricing"] = $total_pricing;
  1736.         $total_pricing += $res['additional_fees_total_price'] + $command_pricing;
  1737.         return $total_pricing;
  1738.     }
  1739.     private function getReducedShippingPrice($data$configs_with_voucher$kabaPoint$res)
  1740.     {
  1741.         $reducedShippingPrice $res['shipping_pricing'];
  1742.         if (isset($data["voucher_id"]) && $data["voucher_id"] != null) {
  1743.             $voucher_billing intval($configs_with_voucher["voucher_billing"]) < $configs_with_voucher["voucher_billing"];
  1744.             $reducedShippingPrice intval($voucher_billing);
  1745.         }
  1746.         if (isset($data['use_kaba_point']) && $data['use_kaba_point']) {
  1747.             $amount intval($kabaPoint["amount_to_reduce"]);
  1748.             $reducedShippingPrice $res["shipping_pricing"] - $amount;
  1749.         }
  1750.         return $reducedShippingPrice;
  1751.     }
  1752.     public function getRemise($big$small)
  1753.     {
  1754.         $remise = (intval($small) * 100) / intval($big);
  1755.         return intval($remise);
  1756.     }
  1757.     private function getCommandPricing($food_command)
  1758.     {
  1759.         $pricing 0;
  1760.         foreach ($food_command as $i => $food) {
  1761.             $pricing += (intval($food['price']) * intval($food["quantity"]));
  1762.         }
  1763.         return $pricing;
  1764.     }
  1765.     private function isOutOfRange($distance)
  1766.     {
  1767.         if ($distance >= 15000)
  1768.             return true;
  1769.         else
  1770.             return false;
  1771.     }
  1772.     private function getCommandDetails($food_command$order_address$shipping_address$voucher_id null$user_id null$use_kaba_point false)
  1773.     {
  1774.         $price 0;
  1775.         $food_litteral "";
  1776.         $is_voucher_used false;
  1777.         $is_billing_voucher_used false;
  1778.         $haveBillingDiscount false;
  1779.         $voucher_billing 0;
  1780.         $voucher_owner_billing_gain 0;
  1781.         $check_voucher_valid $this->checkIfVoucherValid($user_id$voucher_id);
  1782.         $check_voucher_owners =  $this->entityManager->getRepository(VoucherOwner::class)->findOneBy([
  1783.             'voucherId' => $voucher_id
  1784.         ]);
  1785.         $kabaPoint null;
  1786.         $type 1;
  1787.         $user =  $this->entityManager->getRepository(Client::class)->find($user_id);
  1788.         if ($user != null)
  1789.             $type filter_var($user->getUsername(), FILTER_VALIDATE_EMAIL) ? 1;
  1790.         $standard_price $this->shippingPricing($order_address$shipping_address$type);
  1791.         $billing $standard_price["billing"];
  1792.         $voucher_billing intval($billing);
  1793.         $is_voucher_on_billing_already_applyed false;
  1794.         $without_promotion_billing $standard_price["billing"];
  1795.         $without_promotion_billing_for_email $standard_price["email_account_billing"];
  1796.         $without_promotion_billing_for_PhoneNumber $standard_price["phoneNumber_account_billing"];
  1797.         $extra_shipping_pricing intval($standard_price["email_account_billing"]) - intval($standard_price["phoneNumber_account_billing"]);
  1798.         $with_discount_billing_for_email $standard_price["email_account_billing"];
  1799.         $with_discount_billing_for_PhoneNumber $standard_price["phoneNumber_account_billing"];
  1800.         $voucherBillingForPhoneNumber intval($standard_price["phoneNumber_account_billing"]);
  1801.         $voucherBillingForEmail intval($standard_price["email_account_billing"]);
  1802.         foreach ($food_command as $i => $food) {
  1803.             if ($i != 0$food_litteral .= "+";
  1804.             $food_command[$i]["food_entity"] = [];
  1805.             $food_litteral .= $food['name'];
  1806.             $price += (intval($food['price']) * intval($food["quantity"]));
  1807.             $food_command[$i]["food_shipping"] = [];
  1808.             $food_command[$i]["food_shipping"]["shipping_pricing"] = intval($without_promotion_billing);
  1809.             $food_command[$i]["food_shipping"]["phoneNumber_shipping_pricing"] = intval($without_promotion_billing_for_PhoneNumber);
  1810.             $food_command[$i]["food_shipping"]["email_shipping_pricing"] = intval($without_promotion_billing_for_email);
  1811.             if ($check_voucher_valid["valid"] == true) {
  1812.                 if (($check_voucher_valid["type"] == || $check_voucher_valid["type"] == 3)) {
  1813.                     if (!$is_voucher_on_billing_already_applyed) {
  1814.                         if ($check_voucher_valid["category"] == 1) {
  1815.                             $reductions = ($voucher_billing $check_voucher_valid["value"]) / 100;
  1816.                             $voucher_billing -= $reductions;
  1817.                             $voucherBillingForPhoneNumber -= $reductions;
  1818.                             $voucherBillingForEmail -= $reductions;
  1819.                             $is_voucher_used true;
  1820.                             $is_billing_voucher_used true;
  1821.                             $is_voucher_on_billing_already_applyed true;
  1822.                         } else {
  1823.                             $voucher_billing -= $check_voucher_valid["value"];
  1824.                             $voucherBillingForPhoneNumber -= $check_voucher_valid["value"];
  1825.                             $voucherBillingForEmail -= $check_voucher_valid["value"];
  1826.                             $is_voucher_used true;
  1827.                             $is_billing_voucher_used true;
  1828.                             $is_voucher_on_billing_already_applyed true;
  1829.                             $haveBillingDiscount true;
  1830.                         }
  1831.                     }
  1832.                 }
  1833.                 if ($check_voucher_owners != null) {
  1834.                     if ($check_voucher_valid["voucher"] != null) {
  1835.                         $voucher $check_voucher_valid["voucher"];
  1836.                         if ($voucher["is_rewarded"] == 1) {
  1837.                             if ($is_billing_voucher_used && ($voucher["reward_type"] == || $voucher["reward_type"] == 3)) {
  1838.                                 $voucher_owner_billing_gain = (intval($billing) * $voucher["reward_percentage_value"]) / 100;
  1839.                                 break;
  1840.                             }
  1841.                         }
  1842.                     }
  1843.                 }
  1844.             }
  1845.             $food_command[$i]["food_shipping"] = [];
  1846.             $food_command[$i]["food_shipping"]["shipping_pricing"] = intval($without_promotion_billing);
  1847.             $food_command[$i]["food_shipping"]["phoneNumber_shipping_pricing"] = intval($without_promotion_billing_for_PhoneNumber);
  1848.             $food_command[$i]["food_shipping"]["email_shipping_pricing"] = intval($without_promotion_billing_for_email);
  1849.         }
  1850.         $additional_fees $this->getOutOfAppAdditionnalFees($billing$shipping_address$order_address);
  1851.         $additional_fee_total_price $this->getAdditionalFeesTotalPricing($additional_fees);
  1852.         $food_price $price;
  1853.         $food_billing $billing;
  1854.         $data = [];
  1855.         $discount 0;
  1856.         $voucher_billing intval($voucher_billing) < $voucher_billing;
  1857.         if ($is_billing_voucher_used) {
  1858.             $food_billing $voucher_billing;
  1859.             $with_discount_billing_for_email $voucherBillingForEmail;
  1860.             $with_discount_billing_for_PhoneNumber $voucherBillingForPhoneNumber;
  1861.             $haveBillingDiscount true;
  1862.         }
  1863.         $is_kaba_point_used false;
  1864.         $kaba_point_used_amount 0;
  1865.         if ($use_kaba_point) {
  1866.             $kabaPoint $this->getMiniKabaPointBalance($user_id$without_promotion_billing);
  1867.             $data["kaba_point"] = $kabaPoint;
  1868.             $amount intval($kabaPoint["amount_to_reduce"]);
  1869.             if ($kabaPoint['can_be_used']) {
  1870.                 $haveBillingDiscount true;
  1871.                 $is_kaba_point_used true;
  1872.                 if ($amount >= $without_promotion_billing) {
  1873.                     $billing 0;
  1874.                     $food_billing $billing;
  1875.                     $kaba_point_used_amount $without_promotion_billing;
  1876.                     $with_discount_billing_for_email $amount >= $without_promotion_billing_for_email $without_promotion_billing_for_email $amount;
  1877.                     $with_discount_billing_for_PhoneNumber $amount >= $without_promotion_billing_for_PhoneNumber $without_promotion_billing_for_PhoneNumber $amount;
  1878.                 } else {
  1879.                     $kaba_point_used_amount $amount;
  1880.                     $billing $without_promotion_billing $amount;
  1881.                     $food_billing $billing;
  1882.                     $with_discount_billing_for_email $without_promotion_billing_for_email $amount;
  1883.                     $with_discount_billing_for_PhoneNumber $without_promotion_billing_for_PhoneNumber $amount;
  1884.                 }
  1885.             } else {
  1886.                 $data["kaba_point"] = $kabaPoint;
  1887.             }
  1888.         } else {
  1889.             $data["kaba_point"] = $kabaPoint;
  1890.         }
  1891.         $data["voucher_pricing"] = [];
  1892.         $data["voucher_pricing"]["valid"] = $check_voucher_valid["valid"];
  1893.         $data["voucher_pricing"]["shipping_pricing"] = intval($voucher_billing);
  1894.         $data["voucher_pricing"]["total_pricing"] = intval($voucher_billing $additional_fee_total_price);
  1895.         $data["voucher_pricing"]["owner"] = [];
  1896.         if ($voucher_id == null) {
  1897.             $data["voucher_pricing"]["owner"]["is_rewarded"] = null;
  1898.             $data["voucher_pricing"]["owner"]["reward_cash_value"] = null;
  1899.             $data["voucher_pricing"]["owner"]["reward_type"] = null;
  1900.         } else {
  1901.             $data["voucher_pricing"]["owner"]["is_rewarded"] = $check_voucher_valid["voucher"]["is_rewarded"];
  1902.             $data["voucher_pricing"]["owner"]["reward_cash_value"] = $check_voucher_valid["voucher"]["reward_cash_value"];
  1903.             $data["voucher_pricing"]["owner"]["reward_type"] = $check_voucher_valid["voucher"]["reward_type"];
  1904.         }
  1905.         $data["voucher_pricing"]["owner"]["reward_on_billing"] = intval($voucher_owner_billing_gain);
  1906.         $data["is_voucher_used"] = $is_voucher_used;
  1907.         $data["is_billing_voucher_used"] = $is_billing_voucher_used;
  1908.         $data["discount"] = $discount;
  1909.         $data["is_kaba_point_used"] = $is_kaba_point_used;
  1910.         $data["kaba_point_used_amount"] = $kaba_point_used_amount;
  1911.         $data["foods"] = $food_command;
  1912.         $data["food_litteral"] = $food_litteral;
  1913.         $data["food_price"] = $food_price;
  1914.         $data["food_billing"] = $food_billing;
  1915.         $data["food_total"] = $food_price $food_billing;
  1916.         $data["without_promo"]["price"] = intval($additional_fee_total_price);
  1917.         $data["without_promo"]["billing"] = intval($without_promotion_billing);
  1918.         $data["without_promo"]["total"] = intval($without_promotion_billing $additional_fee_total_price);
  1919.         $data["phoneNumber_shipping_pricing"] = intval($with_discount_billing_for_PhoneNumber);
  1920.         $data["email_shipping_pricing"] = intval($with_discount_billing_for_email);
  1921.         $data["base_shipping_pricing"] = intval($standard_price["billing"]);
  1922.         $data["extra_shipping_pricing"] = $extra_shipping_pricing $extra_shipping_pricing 0;
  1923.         $data['additional_fees'] = $additional_fees;
  1924.         $data['additional_fee_total_price'] = $additional_fee_total_price;
  1925.         $data["haveBillingDiscount"] = $haveBillingDiscount;
  1926.         return $data;
  1927.     }
  1928.     private function isFirstCommandBonusApply($id)
  1929.     {
  1930.         $loyalty $this->entityManager->getRepository(Loyalty::class)->findOneBy([
  1931.             "status" => "1"
  1932.         ]);
  1933.         $today = new \DateTime();
  1934.         $countUserCommand count($this->entityManager->getRepository(Command::class)->findBy([
  1935.             'clientId' => $id,
  1936.             'state' => '3'
  1937.         ]));
  1938.         $haveAlredyBonus =  $this->entityManager->getRepository(PayBonus::class)->findOneBy([
  1939.             'clientId' => $id
  1940.         ]);
  1941.         if (
  1942.             $haveAlredyBonus == null &&
  1943.             $loyalty != null &&
  1944.             $today >= $loyalty->getStartDate() &&
  1945.             $today <= $loyalty->getEndDate() &&
  1946.             ($countUserCommand) < intval($loyalty->getRequired())
  1947.         ) {
  1948.             return ['response' => true'type' => $loyalty->getType()];
  1949.         }
  1950.         return ['response' => false'type' => '-1'];
  1951.     }
  1952.     private function getAdress($shipping_address_id)
  1953.     {
  1954.         if ($shipping_address_id == null)
  1955.             return -1;
  1956.         $address $this->entityManager->getRepository(Adresses::class)->find($shipping_address_id);
  1957.         if ($address == null)
  1958.             return -1;
  1959.         $address_in_array $this->addressForMobileToArray($address);
  1960.         return $address_in_array;
  1961.     }
  1962.     private function madeUpCommandItemWithVoucher(Command $command)
  1963.     {
  1964.         $tmp = [];
  1965.         $type 1;
  1966.         $user =  $this->entityManager->getRepository(Client::class)->find($command->getClientId());
  1967.         if ($user != null) {
  1968.             $type filter_var($user->getUsername(), FILTER_VALIDATE_EMAIL) ? 1;
  1969.         }
  1970.         $restaurant $this->entityManager->getRepository(RestaurantConfig::class)->find($command->getRestaurantId());
  1971.         $shipping_address $command->getShippingAddress();
  1972.         $order_shipping_address $command->getOrderShippingAddress();
  1973.         $standard_price $this->shippingPricing($order_shipping_address['id'], $shipping_address['id'], $type);
  1974.         $billing intval($standard_price["billing"]);
  1975.         $promotion_billing intval($command->getShippingPricing());
  1976.         /*check if voucher has been used*/
  1977.         $voucher_billing 0;
  1978.         $voucher_food_price 0;
  1979.         $is_voucher_used 0;
  1980.         $is_food_voucher_used 0;
  1981.         $is_billing_voucher_used 0;
  1982.         $tmp["food_list"] = [];
  1983.         $tmp["order_type"] = $command->getOrderType();
  1984.         $tmp['start_date'] = strval($command->getStartDate());
  1985.         $state intval($command->getState());
  1986.         if ($state == || $state == 3) {
  1987.             $livreur $this->entityManager->getRepository(Livreur::class)->find($command->getLivreurId());
  1988.             if ($livreur != null) {
  1989.                 $tmp["livreur"] = [];
  1990.                 $tmp["livreur"]["id"] = $livreur->getId();
  1991.                 $tmp["livreur"]["name"] = $livreur->getName();
  1992.                 $tmp["livreur"]["workcontact"] = $livreur->getWorkContact();
  1993.                 $pic '';
  1994.                 $employee $this->entityManager->getRepository(Employee::class)->find(intval($livreur->getEmployeeId()));
  1995.                 if ($employee != null) {
  1996.                     $pic 'employee_picture/' $employee->getFileName();
  1997.                 }
  1998.                 $tmp["livreur"]["pic"] = $pic;
  1999.             }
  2000.         }
  2001.         $price_remise 0;
  2002.         $price_command 0;
  2003.         $is_promo 0;
  2004.         $is_preorder 0;
  2005.         foreach ($command->getOrderDetails() as $food) {
  2006.             $price_command += intval($food["price"]) * intval($food["quantity"]);
  2007.             $food["quantity"] = strval($food["quantity"]);
  2008.             $food["price"] = strval($food["price"]);
  2009.             array_push($tmp["food_list"], $food);
  2010.         }
  2011.         $price_remise $price_command;
  2012.         $total_without_remise $price_command $billing;
  2013.         $total_with_remise $price_remise $promotion_billing;
  2014.         $tmp["kaba_point_used_amount"] = 0;
  2015.         if ($command->getKabaPoint() != null) {
  2016.             $is_promo 1;
  2017.             $tmp["kaba_point_used_amount"] = $command->getKabaPointAmount();
  2018.         }
  2019.         $tmp["id"] = $command->getId();
  2020.         $tmp["foods_count"] = count($command->getOrderDetails());
  2021.         $tmp["is_payed_at_arrival"] = $command->getPayAtDelivery();
  2022.         $tmp["state"] = $state;
  2023.         $tmp["infos"] = $command->getInfos();
  2024.         $tmp["restaurant_entity"] = [];
  2025.         $tmp["restaurant_entity"]["id"] = $restaurant->getId();
  2026.         $tmp["restaurant_entity"]["name"] = $restaurant->getName();
  2027.         $tmp["restaurant_entity"]["pic"] = '/' $this->getParameter('rp') . '/' $restaurant->getPic();
  2028.         $tmp["remise"] = $this->getRemise($total_without_remise$total_with_remise);
  2029.         $tmp["out_of_range"] = $standard_price["out_of_range"];
  2030.         $tmp["shipping_address"] = $shipping_address;
  2031.         if (isset($tmp["shipping_address"]["user"])) {
  2032.             $tmp["shipping_address"]["user"] = [];
  2033.         }
  2034.         $tmp["is_promotion"] = $is_promo;
  2035.         $tmp["is_preorder"] = $is_preorder;
  2036.         $tmp["shipping_pricing"] = intval($billing);
  2037.         $tmp["food_pricing"] = intval($price_command);
  2038.         $tmp["total_pricing"] = intval($billing $price_command);
  2039.         $tmp["promotion_shipping_pricing"] = intval($promotion_billing);
  2040.         $tmp["promotion_food_pricing"] = intval($price_remise);
  2041.         $tmp["promotion_total_pricing"] = intval($promotion_billing $price_remise);
  2042.         $tmp["preorder_shipping_pricing"] = intval($promotion_billing);
  2043.         $tmp["preorder_food_pricing"] = intval($price_command);
  2044.         $tmp["preorder_total_pricing"] = intval($promotion_billing $price_command);
  2045.         $tmp["start_delivery"] = $command->getStartOfDelivery();
  2046.         $tmp["end_delivery"] = $command->getEndOfDelivery();
  2047.         $tmp["start_time"] = $command->getStartTime();
  2048.         $tmp["start_date"] = $command->getStartDate();
  2049.         $tmp["voucher_entity"] = [];
  2050.         $voucher_datas $this->processVoucherDatas($command$promotion_billing$billing$price_remise);
  2051.         if ($voucher_datas["is_voucher_used"]) {
  2052.             $tmp["is_promotion"] = 1;
  2053.             $tmp["promotion_food_pricing"] = $voucher_datas["price_remise"];
  2054.             $tmp["promotion_shipping_pricing"] = $voucher_datas["shipping_pricing"];
  2055.             $tmp["promotion_total_pricing"] = intval($voucher_datas["price_remise"]) + intval($voucher_datas["shipping_pricing"]);
  2056.             $tmp["remise"] = '' . ($this->getRemise($total_without_remise$tmp["promotion_total_pricing"]));
  2057.             $tmp["is_voucher_used"] = 1;
  2058.             if ($voucher_datas["voucher_id"] != null) {
  2059.                 $voucher $this->entityManager->getRepository(Voucher::class)->find($voucher_datas["voucher_id"]);
  2060.                 if ($voucher != null) {
  2061.                     $tmp["voucher_entity"] = $this->voucherToArrayLite($voucher);
  2062.                     $tmp["voucher_entity"]["id"] = $voucher->getId();
  2063.                 }
  2064.             }
  2065.         }
  2066.         $tmp["preorder"] = $command->getPreOrder();
  2067.         $tmp["preorder_hour"] = null;
  2068.         if ($command->getPreOrder() == 1) {
  2069.             $preorder_hour $this->entityManager->getRepository(PreorderCommandDetails::class)->findOneBy([
  2070.                 'commandId' => $command->getId()
  2071.             ]);
  2072.             if ($preorder_hour != null) {
  2073.                 $tmp["preorder_hour"]["start"] = $preorder_hour->getStart();
  2074.                 $tmp["preorder_hour"]["end"] = $preorder_hour->getEnd();
  2075.                 $tmp["preorder_discount"] = $preorder_hour->getDiscount();
  2076.             }
  2077.         }
  2078.         $tmp["passphrase"] = $command->getPassPhrase();
  2079.         $tmp["last_update"] = strtotime($command->getLastUpdate());
  2080.         $tmp["reason"] = $command->getReason();
  2081.         $haveBonus $this->entityManager->getRepository(PayBonus::class)->findOneBy(["clientId" => $command->getClientId(), "commandId" => $command->getId()]);
  2082.         if ($haveBonus != null && $haveBonus->getOfferType() == '1') {
  2083.             $tmp["is_promotion"] = 1;
  2084.             $tmp["promotion_total_pricing"] -= $tmp["promotion_shipping_pricing"];
  2085.             $tmp["promotion_shipping_pricing"] = 0;
  2086.             $tmp["preorder_total_pricing"] -= $tmp["preorder_shipping_pricing"];
  2087.             $tmp["preorder_shipping_pricing"] = 0;
  2088.             $tmp["without_voucher_promotion_shipping_pricing"] = 0;
  2089.         }
  2090.         return $tmp;
  2091.     }
  2092.     public function forMobileWithVoucherCommandToArray(Command $command)
  2093.     {
  2094.         $com = [];
  2095.         $type 1;
  2096.         $user  $this->entityManager->getRepository(Client::class)->find($command->getClientId());
  2097.         if ($user != null) {
  2098.             $type filter_var($user->getUsername(), FILTER_VALIDATE_EMAIL) ? 1;
  2099.         }
  2100.         $shipping_address $command->getShippingAddress();
  2101.         $order_address $command->getOrderShippingAddress();
  2102.         $standard_price $this->shippingPricing($order_address['id'], $shipping_address['id'], $type);
  2103.         $billing intval($standard_price["billing"]);
  2104.         $promotion_billing intval($command->getShippingPricing());
  2105.         $price_remise 0;
  2106.         $price_command 0;
  2107.         $is_promo 0;
  2108.         $is_preorder 0;
  2109.         $com["food_list"] = [];
  2110.         if (!empty($command->getOrderDetails()) && is_iterable($command->getOrderDetails())) {
  2111.             foreach ($command->getOrderDetails() as $i => $food_command) {
  2112.                 $food $food_command;
  2113.                 $price_command += intval($food["price"]) * intval($food_command["quantity"]);
  2114.                 $fd = [];
  2115.                 $fd["name"] = $food["name"];
  2116.                 $fd["price"] = strlen($food["price"]) > strval($food["price"]) : "0";
  2117.                 $fd["quantity"] = strlen($food_command["quantity"]) > strval($food_command["quantity"]) : "0";
  2118.                 $fd["pic"] = $food["pic"] ?? "";
  2119.                 array_push($com["food_list"], $fd);
  2120.             }
  2121.         }
  2122.         $state intval($command->getState());
  2123.         if ($state == || $state == 3) {
  2124.             $livreur =  $this->entityManager->getRepository(Livreur::class)->find(intval($command->getLivreurId()));
  2125.             if ($livreur != null) {
  2126.                 $com["livreur"] = $this->livreurToArrayDashboard($livreur);
  2127.             }
  2128.         }
  2129.         $com["kaba_point_used_amount"] = 0;
  2130.         if ($command->getKabaPoint() != null) {
  2131.             $is_promo 1;
  2132.             $com["kaba_point_used_amount"] = $command->getKabaPointAmount();
  2133.         }
  2134.         $client $this->entityManager->getRepository(Client::class)->find(intval($command->getClientId()));
  2135.         $com["id"] = $command->getId();
  2136.         $com["customer_username"] = '';
  2137.         if ($client != null) {
  2138.             $com["customer_username"] = $client->getUsername();
  2139.         }
  2140.         $com["restaurant_entity"] = [];
  2141.         $restaurant $this->entityManager->getRepository(RestaurantConfig::class)->find($command->getRestaurantId());
  2142.         $com["restaurant_entity"]["id"] = $restaurant->getId();
  2143.         $com["restaurant_entity"]["name"] = $restaurant->getName();
  2144.         $com["restaurant_entity"]["pic"] = '/' $this->getParameter('rp') . '/' $restaurant->getPic();
  2145.         $com["shipping_address"] = $shipping_address;
  2146.         if (isset($com["shipping_address"]["user"])) {
  2147.             $com["shipping_address"]["user"] = [];
  2148.         }
  2149.         $com["is_promotion"] = $is_promo;
  2150.         $com["is_preorder"] = $is_preorder;
  2151.         $com["shipping_pricing"] = intval($billing);
  2152.         $com["food_pricing"] = $price_command;
  2153.         $com["total_pricing"] = $billing $price_command;
  2154.         $com["promotion_shipping_pricing"] = $promotion_billing;
  2155.         $com["promotion_food_pricing"] = $price_command;
  2156.         $com["without_voucher_promotion_shipping_pricing"] = $billing;
  2157.         $com["without_voucher_promotion_food_pricing"] = $price_command;
  2158.         $com["promotion_total_pricing"] = $promotion_billing $price_command;
  2159.         $com["preorder_shipping_pricing"] = $promotion_billing;
  2160.         $com["preorder_food_pricing"] = $price_command;
  2161.         $com["preorder_total_pricing"] = $promotion_billing $price_command;
  2162.         $com["is_voucher_used"] = 0;
  2163.         $com["preorder"] = $command->getPreOrder();
  2164.         $com["preorder_hour"] = null;
  2165.         if ($command->getPreOrder() == 1) {
  2166.             $preorder_hour $this->entityManager->getRepository(PreorderCommandDetails::class)->findOneBy([
  2167.                 'commandId' => $command->getId()
  2168.             ]);
  2169.             if ($preorder_hour != null) {
  2170.                 $com["preorder_hour"]["start"] = $preorder_hour->getStart();
  2171.                 $com["preorder_hour"]["end"] = $preorder_hour->getEnd();
  2172.                 $com["preorder_discount"] = "" $preorder_hour->getDiscount();
  2173.             }
  2174.         }
  2175.         $com["foods_count"] = count($command->getFoodCommand());
  2176.         $com["last_update"] = strtotime($command->getLastUpdate());
  2177.         $com["last_update_sample"] = $command->getLastUpdate();
  2178.         $com["start_time"] = $command->getStartTime();
  2179.         $com["start_date"] = $command->getStartDate();
  2180.         $com["state"] = $state;
  2181.         $com["infos"] = $command->getInfos() ?? "";
  2182.         $com["reason"] = $command->getReason();
  2183.         $com["passphrase"] = $command->getPassPhrase();
  2184.         $com["is_payed_at_arrival"] = $command->getPayAtDelivery();
  2185.         $com["order_type"] = $command->getOrderType();
  2186.         $rating 0;
  2187.         $comment '';
  2188.         $repo $this->entityManager->getRepository(DeliveryRating::class);
  2189.         $rate $repo->findOneBy([
  2190.             'commandId' => $command->getId()
  2191.         ]);
  2192.         if ($rate != null) {
  2193.             $rating $rate->getRating()??0;
  2194.             $comment $rate->getComment();
  2195.         }
  2196.         $com["rating"] = $rating;
  2197.         $com["comment"] = $comment;
  2198.         $com["voucher_entity"] = [];
  2199.         $voucher_datas $this->processVoucherDatas($command$promotion_billing$billing$price_remise);
  2200.         if ($voucher_datas["is_voucher_used"]) {
  2201.             $com["is_promotion"] = 1;
  2202.             $com["promotion_shipping_pricing"] = $voucher_datas["shipping_pricing"];
  2203.             $com["promotion_total_pricing"] = intval($price_command) + intval($voucher_datas["shipping_pricing"]);
  2204.             $com["is_voucher_used"] = 1;
  2205.             if ($voucher_datas["voucher_id"] != null) {
  2206.                 $voucher $this->entityManager->getRepository(Voucher::class)->find($voucher_datas["voucher_id"]);
  2207.                 if ($voucher != null) {
  2208.                     $com["voucher_entity"] = $this->voucherToArrayLite($voucher);
  2209.                 }
  2210.             }
  2211.         }
  2212.         $haveBonus $this->entityManager->getRepository(PayBonus::class)->findOneBy(["clientId" => $user->getId(), "commandId" => $command->getId()]);
  2213.         if ($haveBonus != null && $haveBonus->getOfferType() == '1') {
  2214.             $com["is_promotion"] = 1;
  2215.             $com["promotion_total_pricing"] -= $com["promotion_shipping_pricing"];
  2216.             $com["promotion_shipping_pricing"] = 0;
  2217.             $com["preorder_total_pricing"] -= $com["preorder_shipping_pricing"];
  2218.             $com["preorder_shipping_pricing"] = 0;
  2219.             $com["without_voucher_promotion_shipping_pricing"] = 0;
  2220.         }
  2221.         return $com;
  2222.     }
  2223.     public function processVoucherDatas($command$shipping_pricing$billing$price_remise)
  2224.     {
  2225.         /*check if voucher has been used*/
  2226.         $check_voucher_usage $this->entityManager->getRepository(VoucherUsage::class)->findOneBy([
  2227.             'commandId' => $command->getId(),
  2228.             'userId' => $command->getClientId(),
  2229.         ]);
  2230.         $voucher_id null;
  2231.         if ($check_voucher_usage != null) {
  2232.             $voucher_id $check_voucher_usage->getVoucherId();
  2233.         }
  2234.         $get_voucher_datas $this->getVoucherApplyDatas($command->getClientId(), $voucher_id);
  2235.         $voucher_billing 0;
  2236.         $voucher_food_price 0;
  2237.         $is_voucher_used false;
  2238.         $is_food_voucher_used false;
  2239.         $is_billing_voucher_used false;
  2240.         $is_voucher_on_billing_already_applyed false;
  2241.         $com = [];
  2242.         $com["price_remise"] = intval($price_remise);
  2243.         $com["shipping_pricing"] = intval($shipping_pricing);
  2244.         $com["is_voucher_used"] = false;
  2245.         $com["is_billing_promotion"] = false;
  2246.         $com["voucher_id"] = $voucher_id;
  2247.         $voucher_billing intval($billing);
  2248.         foreach ($command->getFoodCommand() as $food_command) {
  2249.             $food $food_command["food_entity"];
  2250.             /*voucher */
  2251.             $vouch_price intval($food["price"]) * intval($food_command["quantity"]);
  2252.             $reduction 0;
  2253.             if ($get_voucher_datas["valid"] == true) {
  2254.                 /*check if that food is in array of concerned foods*/
  2255.                 if (
  2256.                     in_array(intval($food["id"]), $get_voucher_datas["products"])
  2257.                     || sizeof($get_voucher_datas["products"]) == 0  /*coz if products =[] it means all foods are selected*/
  2258.                 ) {
  2259.                     if ($get_voucher_datas["type"] == || $get_voucher_datas["type"] == 3) { /* reduction on food or all*/
  2260.                         if ($get_voucher_datas["category"] == 1) {
  2261.                             /*in percent*/
  2262.                             $reduction = (intval($food["price"]) * $get_voucher_datas["value"]) / 100;
  2263.                             $is_voucher_used true;
  2264.                             $is_food_voucher_used true;
  2265.                         } else {
  2266.                             $reduction $get_voucher_datas["value"];
  2267.                             $is_voucher_used true;
  2268.                             $is_food_voucher_used true;
  2269.                         }
  2270.                     }
  2271.                 }
  2272.                 if ($get_voucher_datas["type"] == || $get_voucher_datas["type"] == 3) {
  2273.                     if (
  2274.                         in_array("" $command->getRestaurantId(), $get_voucher_datas["restaurant_allowed"])
  2275.                         || sizeof($get_voucher_datas["restaurant_allowed"]) == 0  /*coz if restaurant_allowed =[] it means all restos are selected*/
  2276.                     ) {
  2277.                         if (!$is_voucher_on_billing_already_applyed) {
  2278.                             if ($get_voucher_datas["category"] == 1) {
  2279.                                 /*in percent*/
  2280.                                 $reductions = ($voucher_billing $get_voucher_datas["value"]) / 100;
  2281.                                 $voucher_billing -= $reductions;
  2282.                                 $is_voucher_used true;
  2283.                                 $is_billing_voucher_used true;
  2284.                                 $is_voucher_on_billing_already_applyed true;
  2285.                             } else {
  2286.                                 $voucher_billing -= intval($get_voucher_datas["value"]);
  2287.                                 $is_voucher_used true;
  2288.                                 $is_billing_voucher_used true;
  2289.                                 $is_voucher_on_billing_already_applyed true;
  2290.                             }
  2291.                         }
  2292.                     }
  2293.                 }
  2294.             }
  2295.             $final_food_price $vouch_price - ($reduction intval($food_command["quantity"]));
  2296.             $voucher_food_price += $final_food_price;
  2297.         }
  2298.         if ($check_voucher_usage != null && $is_voucher_used) {
  2299.             $voucher_food_price intval($voucher_food_price) < $voucher_food_price;
  2300.             $voucher_billing intval($voucher_billing) < $voucher_billing;
  2301.             if ($is_food_voucher_used) {
  2302.                 $com["price_remise"] = $voucher_food_price;
  2303.             }
  2304.             if ($is_billing_voucher_used) {
  2305.                 $com["shipping_pricing"] = $voucher_billing;
  2306.                 $com["is_billing_promotion"] = true;
  2307.             }
  2308.             $com["is_voucher_used"] = true;
  2309.         }
  2310.         return $com;
  2311.     }
  2312.     private function createColisFoods($products)
  2313.     {
  2314.         $menu $this->entityManager->getRepository(Menu::class)->findOneBy(['name' => "KABA_COLIS"]);
  2315.         $resto $this->entityManager->getRepository(RestaurantConfig::class)->findOneBy([
  2316.             'username' => "kaba_colis"
  2317.         ]);
  2318.         $foods = [];
  2319.         if (!$menu) {
  2320.             $menu = new Menu();
  2321.             $menu->setName("KABA_COLIS");
  2322.             $menu->setDescription("Le menu des commandes colis");
  2323.             $menu->setPic("");
  2324.             $menu->setState(1);
  2325.             $menu->setPromotion(0);
  2326.             $menu->setRestaurantId($resto->getId());
  2327.             $menu->setDeleted(0);
  2328.             $menu->setPriority(1);
  2329.             $menu->setLastUpdate(date("d-m-Y H:i:sa"));
  2330.             $em $this->entityManager;
  2331.             $em->persist($menu);
  2332.             $em->flush();
  2333.         }
  2334.         $res =  $this->createOutOfAppFoods($products$menu$resto);
  2335.         return $res;
  2336.     }
  2337.     private function createHorsAppliFoods($products)
  2338.     {
  2339.         $menu $this->entityManager->getRepository(Menu::class)->findOneBy(['name' => "HORS_APPLI"]);
  2340.         $resto $this->entityManager->getRepository(RestaurantConfig::class)->findOneBy([
  2341.             'username' => "hors_appli"
  2342.         ]);
  2343.         $foods = [];
  2344.         if (!$menu) {
  2345.             $menu = new Menu();
  2346.             $menu->setName("HORS_APPLI");
  2347.             $menu->setDescription("Le menu des commandes hors appli");
  2348.             $menu->setPic("");
  2349.             $menu->setState(1);
  2350.             $menu->setPromotion(0);
  2351.             $menu->setRestaurantId($resto->getId());
  2352.             $menu->setDeleted(0);
  2353.             $menu->setPriority(1);
  2354.             $menu->setLastUpdate(date("d-m-Y H:i:sa"));
  2355.             $em $this->entityManager;
  2356.             $em->persist($menu);
  2357.             $em->flush();
  2358.         }
  2359.         $res =  $this->createOutOfAppFoods($products$menu$resto);
  2360.         return $res;
  2361.     }
  2362.     private function createOutOfAppFoods($products$menu$resto)
  2363.     {
  2364.         $normalizer = new Serializer([new ObjectNormalizer()]);
  2365.         $foods = [];
  2366.         foreach ($products as $food) {
  2367.             $new_food = new Food();
  2368.             $new_food->setMenuId($menu->getId());
  2369.             $new_food->setName($food['name']);
  2370.             $new_food->setDescription("");
  2371.             $new_food->setPriority(1);
  2372.             $new_food->setDeleted(0);
  2373.             $new_food->setRestaurantId($resto->getId());
  2374.             $new_food->setRestaurant($resto);
  2375.             $new_food->setCategory(1);
  2376.             $new_food->setPromotion(0);
  2377.             $new_food->setState(1);
  2378.             $new_food->setPic($food['image']);
  2379.             $new_food->setPrice($food['price']);
  2380.             $new_food->setPromotionPrice($food['price']);
  2381.             $new_food->setFoodDetailsPictures([$food['image']]);
  2382.             $new_food->setLastUpdate(date("d-m-Y H:i:sa"));
  2383.             $em $this->entityManager;
  2384.             $em->persist($new_food);
  2385.             $em->flush();
  2386.             array_push($foods, [
  2387.                 'food_id' => $new_food->getId(),
  2388.                 'quantity' => $food['quantity'],
  2389.                 'food_entity' => $normalizer->normalize($new_food),
  2390.                 'food_shipping' => $food['food_shipping']
  2391.             ]);
  2392.         }
  2393.         return $foods;
  2394.     }
  2395.     private function applySubscriptionOnOrder($distance$subscriptionData$promotion_shipping_pricing)
  2396.     {
  2397.         $promotion_shipping_pricing $promotion_shipping_pricing;
  2398.     
  2399.         try {
  2400.             if (!$subscriptionData || empty($subscriptionData)) {
  2401.                 return $promotion_shipping_pricing;
  2402.             }
  2403.           $packData $subscriptionData['pack'] ?? null;
  2404.             if (!$packData) {
  2405.                 return $promotion_shipping_pricing;
  2406.             }
  2407.             $endDate = isset($subscriptionData['end_date']) ? new DateTime($subscriptionData['end_date']) : null;
  2408.             $now = new DateTime();
  2409.             $isBefore $endDate ? ($now $endDate) : false;
  2410.     
  2411.             $radius_limit = isset($packData['radius_km']) ? floatval($packData['radius_km']) : 0;
  2412.             $delivery_limit = isset($packData['deliverylimit']) ? intval($packData['deliverylimit']) : 0;
  2413.             $usage_count = isset($subscription['alreadyUsed']) ? intval($subscription['alreadyUsed']) : 0;
  2414.            if (!$isBefore) {
  2415.                 return $promotion_shipping_pricing;
  2416.             }
  2417.     
  2418.             if ($distance < ($radius_limit 1000)) {
  2419.                 $promotion_shipping_pricing 0;
  2420.                 return $promotion_shipping_pricing;
  2421.             }
  2422.     
  2423.             if ($usage_count $delivery_limit) {
  2424.                 $promotion_shipping_pricing 0;
  2425.                 return $promotion_shipping_pricing;
  2426.             }
  2427.     
  2428.         } catch (Exception $e) {
  2429.             error_log("Error in applySubscriptionOnOrder: " $e->getMessage());
  2430.         }
  2431.     
  2432.         return $promotion_shipping_pricing;
  2433.     }
  2434.     
  2435.     private function checkNumberOfOrderFoUser($id){
  2436.         $client $this->entityManager->getRepository(Client::class)->find($id);
  2437.         if($client){
  2438.             $qb $this->entityManager->createQueryBuilder(); 
  2439.             $qb->select('COUNT(c.id)')
  2440.             ->from(Command::class,'c')
  2441.             ->where('c.clientId = :client_id')
  2442.             ->setParameter('client_id',$id);
  2443.             return (int) $qb->getQuery()->getSingleScalarResult();
  2444.         }else{
  2445.             return -1;
  2446.         }
  2447.     }
  2448. }