<?php
require "conn.php";



$OrderID  = $_POST["OrderID"];
$DriverID  = $_POST["DriverID"];


$Token = "s";

foreach (getallheaders() as $name => $value) { 

	if($name == "token"){
		
		$Token = $value;
	
	}
	
} 

$test=0;

	$res = mysqli_query($con,"SELECT * FROM Drivers WHERE DriverToken='$Token'");
	while($row = mysqli_fetch_assoc($res)){
		
		
		$test=4;
		$FName = $row["FName"];
		$PersonalPhoto = $row["PersonalPhoto"];
		

	}
	
	if(true){
	    
	    
	    $res = mysqli_query($con,"SELECT * FROM Orders JOIN Shops ON Orders.ShopID = Shops.ShopID WHERE OrderID=$OrderID");
	while($row = mysqli_fetch_assoc($res)){
		
		
	$Type =	$row["Type"];
	$ShopName  = $row["DestinationName"];
	$ShopPhoto = $row["DestnationPhoto"];
	$OrderPriceFromShop = $row["OrderPriceFromShop"];
	$ShopID = $row["ShopID"];
	$Method = $row["Method"];
	$CategoryID = $row["CategoryID"];
		
		$test=4;

	}
	    
	    if($Type == "Other"){
	    
	    $Paid = 'Paid';
		$ShopRecive = 'YES';
		
		if($Method!="CASH"){
		   $Paid	   = 'NotPaid'; 
			
		}
	    
	    }else{
			
		   $res = mysqli_query($con,"SELECT disUser,percent FROM OrdersJiblerpercentage");
                        
                                        $result = array();
                        
                                        while($row = mysqli_fetch_assoc($res)){
                                       
											$disUser = $row["disUser"];
											$percentShop = $row["percent"];
                                                               
                                        }
										
		    $res = mysqli_query($con,"SELECT PercForOrder FROM Categories WHERE CategoryId = $CategoryID");
                        
                                        $result = array();
                        
                                        while($row = mysqli_fetch_assoc($res)){
                                       
											$percentShop = $row["PercForOrder"];
                                                               
                                        }							
										
										
			$ShopFees = $OrderPriceFromShop * $percentShop / 100;							
			
			$ChangedBalance = $OrderPriceFromShop - $ShopFees;
			
	       $Paid	= 'NotPaid'; 
		   $ShopRecive = 'NO';
		   
		   if($Method!="CASH"){
		   $Paid	   = 'NotPaid'; 
			
		   }
		   
		   
		   
		   
		   
		   if($Method=="CASH"){
			   $sql="UPDATE Shops SET Balance=Balance+$ChangedBalance WHERE ShopID=$ShopID";
			   if(mysqli_query($con,$sql))
			   {}
		   }else{
			   $sql="UPDATE Shops SET Balance=Balance-$ShopFees WHERE ShopID=$ShopID";
			   if(mysqli_query($con,$sql))
			   {}
		   }
		   
		   $sql="INSERT INTO SlasesRevTransaction (OrderID,ShopID,TotalPrice,CutPers) VALUES ('$OrderID','$ShopID','$OrderPriceFromShop','$ShopFees');";
			   if(mysqli_query($con,$sql))
			   {}
		   
		   $sql="UPDATE Money SET TotalIncome=TotalIncome+$ShopFees,SalesR=SalesR+$ShopFees";
			   if(mysqli_query($con,$sql))
			   {}
	        
	    }
		
    $res = mysqli_query($con,"SELECT DriverCommesion FROM MoneyStop");
	while($row = mysqli_fetch_assoc($res)){
		
		$DriverCommesion = $row["DriverCommesion"];
		
	}	
		

   $sql="UPDATE Orders SET OrderState='Done',PaidForDriver = '$Paid',ShopRecive = '$ShopRecive',DriverOmola = '$DriverCommesion' WHERE OrderID=$OrderID";
   if(mysqli_query($con,$sql))
   {
	   
	   $sql="UPDATE Drivers SET DriverOrdersNum=DriverOrdersNum+1 WHERE DriverID=$DriverID";
	   if(mysqli_query($con,$sql))
       {
		   
	   }
	   
	   
	   $OrderPrice = "0";
	   $res = mysqli_query($con,"SELECT * FROM Orders WHERE OrderID=$OrderID");
	    while($row = mysqli_fetch_assoc($res)){
		
		
		$OrderPrice = $row["OrderPrice"];
		
		$test=4;

	    }
	
	   
	   
	   $sql="UPDATE Drivers SET DriverOrdersNum=DriverOrdersNum+1,TotolEarnMoney=TotolEarnMoney+$OrderPrice WHERE DriverID=$DriverID";
	   if(mysqli_query($con,$sql))
       {
		   
	   }
	   
	    
	   
	
	$message ="Finished Sucssessfuly";
    $success = true;
    $status_code = 200;
	$result = []; 
    echo json_encode(array('status_code' => $status_code,'success' => $success ,"data"=>$result,"message"=>$message));
    
    
    $res = mysqli_query($con,"SELECT * FROM Orders WHERE OrderID=$OrderID");

    $UserID = 0;
	$ShopID = 0;
    
        $result = array();

            while($row = mysqli_fetch_assoc($res)){
            //$data = $row[0];
            $result[] = $row;
            $UserID = $row["UserID"];
			$ShopID = $row["ShopID"];
			$DestinationName = $row["DestnationCitiesID"];
			$Method          = $row["Method"];
			$UserCitiesID          = $row["UserCitiesID"];

    }
    
    $sql="INSERT INTO UserNotification (OrderID,UserID,NotificationText) VALUES ('$OrderID','$UserID','Votre numéro de commande $OrderID a été livré');";
   if(mysqli_query($con,$sql))
   {
       
       $res = mysqli_query($con,"SELECT * FROM Users WHERE UserID=$UserID");
			
			$UserFirebaseToken = "";

		$result = array();

			while($row = mysqli_fetch_assoc($res)){

			//$data = $row[0];
			$result[] = $row;
			$test=4;
			
			$UserFirebaseToken = $row["UserFirebaseToken"];
			$UserPhoto         = $row["UserPhoto"];
			$LANG = $row["LANG"];

			}
			
			
			
			/////////////transaction ///////
			
			$Moneys = $OrderPriceFromShop + $OrderPrice ;
			
			
			
			$res = mysqli_query($con,"SELECT * FROM Drivers WHERE DriverID=$DriverID");
	while($row = mysqli_fetch_assoc($res)){
		
		
		$test=4;
		$FName = $row["FName"];
		$PersonalPhoto = $row["PersonalPhoto"];
		

	}
	
							$disUser = 0;
				
				$res = mysqli_query($con,"SELECT disUser,percent FROM OrdersJiblerpercentage");
                        
                                        $result = array();
                        
                                        while($row = mysqli_fetch_assoc($res)){
                        
                                       
										$disUser = $row["disUser"];
										$percentShop = $row["percent"];
                                                               
                                        }
										
										if($disUser<3){
											$disUser = 3;
										}
										
				$res = mysqli_query($con,"SELECT PercForOrder FROM Categories WHERE CategoryId = $CategoryID");
                        
                                        $result = array();
                        
                                        while($row = mysqli_fetch_assoc($res)){
                                       
											$percentShop = $row["PercForOrder"];
                                                               
                                        }							
	
				$disUser = ($OrderPriceFromShop * $disUser / 100);
				$Moneys  = $Moneys + $disUser;
				
				$ShopFees= $OrderPriceFromShop *$percentShop / 100;
			
			 $sql="INSERT INTO UserTransaction (UserID,Money,Method,DistnationName,DistnationPhoto,DriverID,OrderID,DriverName,Driverphoto,MoneyPlusOrLess,UserFees) VALUES ('$UserID','$Moneys','$Method','$ShopName','$ShopPhoto','$DriverID','$OrderID','$FName','$PersonalPhoto','less','$disUser');";
			   if(mysqli_query($con,$sql))
			   {}
		   
		   $sql="INSERT INTO FeesTransaction (UserID,OrderID,Money) VALUES ('$UserID','$OrderID','$disUser');";
			   if(mysqli_query($con,$sql))
			   {}
		  
		    
		  $sql="UPDATE Money SET TotalIncome=TotalIncome+$disUser,ServComm=ServComm+$disUser";
			   if(mysqli_query($con,$sql))
			   {}
		   
		 //  $sql="INSERT INTO DriverTransactions (DriverID,Address,SubAddress,Money) 
		//	  VALUES ('$DriverID','$ShopName','jibler_payment','$Moneys');";
		//	  if(mysqli_query($con,$sql))
		//	  {}
	
				$res = mysqli_query($con,"SELECT * FROM MoneyStop");

							$result = array();
$DriverCommesionN = 0;
							while($row = mysqli_fetch_assoc($res)){


							$DriverCommesionN = $row["DriverCommesion"];
							
							
							}
			
			
		   $sql="INSERT INTO DriverRevTransaction (DriverID,OrderID,DeliveryZoneID,Money) VALUES ('$DriverID','$OrderID','$UserCitiesID','$DriverCommesionN');";
			   if(mysqli_query($con,$sql))
			   {}

		   $sql="UPDATE Money SET TotalIncome=TotalIncome+$DriverCommesionN,DeliveryR=DeliveryR+$DriverCommesionN";
			   if(mysqli_query($con,$sql))
			   {} 		
	
		   
		   $sql="INSERT INTO DriverTransactions (Address,SubAddress,Money,DriverID,TransToken,TransationPhoto,PayMethod,UserPhoto,OrderID,fees) VALUES ('$ShopName','$FName','$Moneys','$DriverID','NONO','$ShopPhoto','$Method','$UserPhoto','$OrderID','$DriverCommesionN');";
			   if(mysqli_query($con,$sql))
			   {}
			
			///////////// transaction /////
			
			$sql="INSERT INTO ShopLastTransaction (ShopID,Money,Method,TransactionName,TransactionPhoto,DriverPhoto,DriverName,TransactionStatus,OrderID,fees) VALUES ('$ShopID','$OrderPriceFromShop','$Method','$DestinationName','Shop','$FName','$PersonalPhoto','Done','$OrderID','$ShopFees');";
			   if(mysqli_query($con,$sql))  
			   {}
			
			
			if($Method=="WALLET"){
				

				

				
				$sql="UPDATE Users SET Balance = Balance-$Moneys WHERE UserID = $UserID";
				   if(mysqli_query($con,$sql))
				   {}
				  
			}
			
			
       if($LANG=="EN"){
						
						$Title = "Delivery Successful! ✅";
						$messagebody = "Congratulations! Your order has been delivered successfully. We
hope you're delighted with your purchase. If you have any feedback or
questions, feel free to reach out. Thank you for choosing our service, and
we look forward to serving you again soon!";
						
					}else if($LANG=="FR"){
						$Title = "Livraison réussie ! ✅";
						$messagebody = "Félicitations ! Votre commande a été livrée avec succès. Nous
espérons que vous êtes satisfait de votre achat. Si vous avez des
commentaires ou des questions, n'hésitez pas à nous contacter. Merci
d'avoir choisi notre service, et nous avons hâte de vous servir à nouveau
bientôt !
";
					}else{
						$Title = "تم التوصيل بنجاح ✅";
						$messagebody = " تم تسليم طلبك بنجاح. نأمل أن تكون راضًيا عن عملية الشراء. إذا كان لديك أي تعليقات أو أسئلة، فال تتردد في التواصل معنا. شكًرا الختيارك خدمتنا، !ونتطلع إلى خدمتك مرة أخرى قريًبا";
					}
          
       send_notification($UserFirebaseToken,$Title,$messagebody,$OrderID);
	   newNotfi($UserFirebaseToken,$Title,$messagebody,$OrderID,$accessToken,$ProgID);
   }
    

   }
   else
   {

	$message ="Error Updated";
    $success = false;
    $status_code = 200;
	$result = []; 
    echo json_encode(array('status_code' => $status_code,'success' => $success ,"data"=>$result,"message"=>$message));

   }
   
	}
	
	else{
		
		
			$message ="Error Token Eror";
			$success = true;
			$status_code = 200;
			$result = []; 
   echo json_encode(array('status_code' => $status_code,'success' => $success ,"data"=>$result,"message"=>$message));
		
	}
	
	function send_notification($UserFirebaseToken,$Titlew,$messagebodyw,$OrderID)
	{
		$url = 'https://fcm.googleapis.com/fcm/send';
		$fields =array(
			 'to' => $UserFirebaseToken,
			 'notification'=>array(
			 'title' => $Titlew,
			 'body' => $messagebodyw,
			 "link"=> "http://sae-marketing.com/$OrderID",
			 "color"=>'$OrderID',
			 'data'=>'$OrderID')
			);

		$headers = array(
			'Authorization:key=AAAAEDOF67k:APA91bFMPNwvWHetPtqc1i--ztKxrPdSd7ZbTXvrm0LWFV6KHlkw5I-9yOdt6ZtBq1PXo3uVEDcJnFmbAKpNH7tTS9wiKLjAaeLzB0J0KMI6xvsZ5z0C-4Kn98VzSLp_fJs-ibpmOJY2',
			'Content-Type:application/json'
			);

	   $ch = curl_init();
       curl_setopt($ch, CURLOPT_URL, $url);
       curl_setopt($ch, CURLOPT_POST, true);
       curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
       curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);  
       curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
       curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
       $result = curl_exec($ch);           
       if ($result === FALSE) {
           die('Curl failed: ' . curl_error($ch));
       }
       curl_close($ch);
       return $result;
	} 
	
	
	function newNotfi($tokens,$TitleW,$MesBodyW,$OrderID,$accessTokenw,$Pid)
	{

		$url = 'https://fcm.googleapis.com/v1/projects/'.$Pid.'/messages:send';
		$fields =array(
			 'to' => $tokens,
			 'notification'=>array(
				 'title' => $TitleW, 
				 'body' => $MesBodyW)
			);

        $fields = array(
            'message' => array(
                'token' => $tokens,
                'notification' => array(
                    'title' => $TitleW,
                    'body' => $MesBodyW
                )
            )
        );

		$headers = array(         
			'Authorization:Bearer '.$accessTokenw,
			'Content-Type:application/json'
			);

	   $ch = curl_init();
       curl_setopt($ch, CURLOPT_URL, $url);
       curl_setopt($ch, CURLOPT_POST, true);
       curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    //   curl_setopt($ch, CURLOPT_HTTPHEADER, array('Host: fcm.googleapis.com'));
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
       curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);  
       curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
       curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
       $result = curl_exec($ch);           
       if ($result === FALSE) {
           die('Curl failed: ' . curl_error($ch));
       }
       curl_close($ch);
       return $result;
	}
	
	
die;
mysqli_close($con);
?>