<?php

require "conn.php";
$test=0;

$DriverID = $_POST["DriverID"];
$OrderId = $_POST["OrderId"];
$Price = $_POST["Price"];
$OrderType = $_POST["OrderType"];



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

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

//	echo $Token;

$test=0;

	$res = mysqli_query($con,"SELECT * FROM Drivers WHERE DriverToken='$Token'");
	while($row = mysqli_fetch_assoc($res)){
		
		
		$test=90;

	}
	
	if(true){

$res = mysqli_query($con,"SELECT * FROM DriversOffer WHERE DriverID ='$DriverID' AND OrderId='$OrderId'");

$result = array();



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

//$data = $row[0];
$result[] = $row;

$test=4;

}
/////////////
//echo json_encode(array("result"=>$result));
if($test==4){
	
    $message ="You ordered before";
    $success = false;
	$result = [];
    $status_code = 200;

echo json_encode(array('status_code' => $status_code,'success' => $success ,"data"=>$result,"message"=>$message));
}
else{
	
	$UserID = "";
	$res = mysqli_query($con,"SELECT * FROM Orders WHERE OrderID ='$OrderId' AND OrderState='waiting'");

	$result = array();



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

	//$data = $row[0];
	$result[] = $row;
	
	$UserID = $row["UserID"];

	$test=9;

	}
	
	if($test==9){
		
		
		
		$res = mysqli_query($con,"SELECT * FROM Drivers WHERE DriverID =$DriverID AND DriverState='Active'");

	$result = array();



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

	//$data = $row[0];
	
	$FName = $row["FName"]; 
	$result[] = $row;
	
//	$UserID = $row["UserID"];

	$test=20;

	}
		
		
	if($test==20){	
		
		
		
	$res = mysqli_query($con,"SELECT * FROM Orders WHERE DelvryId =$DriverID AND OrderState='Doing'");

	$result = array();


    $nums = 0;

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

	//$data = $row[0];
	$result[] = $row;
	
//	$UserID = $row["UserID"];

	$test=30;
	$nums++;

	}
		
	if($nums<7){
		
		$sql="INSERT INTO DriversOffer (DriverID,OrderId) VALUES ('$DriverID','$OrderId');";
   if(mysqli_query($con,$sql))
   {
	   
	if($OrderType=="SLOW"){   
	   $sql="UPDATE Orders SET OrderState='Doing' , DelvryId = '$DriverID', OrderPrice = '$Price' WHERE OrderID=$OrderId";
	   if(mysqli_query($con,$sql))
	   {}
	}
	   
	   $UserFirebaseToken = "";
	   
	   $res = mysqli_query($con,"SELECT * FROM Users WHERE UserID=$UserID");
		while($row = mysqli_fetch_assoc($res)){
		
		
		$UserFirebaseToken = $row["UserFirebaseToken"];
		$LANG 			   = $row["LANG"];
		
		$test=4;
		
    $sql="INSERT INTO UserNotification (OrderID,UserID,NotificationText) VALUES ('$OrderId','$UserID','Vous avez une nouvelle offre en ordre $OrderId');";
   if(mysqli_query($con,$sql))
   {
   }
		
		send_notification($UserFirebaseToken,$OrderId,$FName,$LANG,$Price);
		newNotfi($UserFirebaseToken,$OrderId,$FName,$LANG,$Price,$accessToken,$ProgID);
	}
	   
	   
	   $message ="Done";
    $success = true;
    $status_code = 200;
	$result = []; 
   echo json_encode(array('status_code' => $status_code,'success' => $success ,"data"=>$result,"message"=>$message));

   }
   
	}else{
	    
	    $message ="برجاء انهاء الطلبات السابقة قبل التقديم في طلبات جديدة";
		$success = false;
		$status_code = 200;
		$result = []; 
		echo json_encode(array('status_code' => $status_code,'success' => $success ,"data"=>$result,"message"=>$message));
	    
	}
		
	} else{
		
		$message ="تواصل مع الاداره لتفعيل الحساب عبر الواتس اب";
		$success = false;
		$status_code = 200;
		$result = []; 
		echo json_encode(array('status_code' => $status_code,'success' => $success ,"data"=>$result,"message"=>$message));
	}
		
	}else{
		
		$message ="العرض لم يعد موجود";
		$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($DriverToken,$OrderID,$FNamew,$LANGw,$Moneyw)
	{
		if($LANGw=="AR"||$LANGw=="ar"){
			$Title = $FNamew . " في طريقه الي استلام";
			$body  = $FNamew . " قد قدم عرًضا لتوصيل طلبك بقيمة " . $Moneyw . "درهم مغربي"; 
		}else if($LANGw=="EN"||$LANGw=="en"){
			$Title = $FNamew . " is on their way to pick up your order";
			$body  = $FNamew . " has offered to deliver your order for " . $Moneyw . "MAD"; 
		}else if($LANGw=="FR"||$LANGw=="fr"){
			$Title = $FNamew . " est en route pour récupérer votre commande";
			$body  = $FNamew . " a proposé de livrer votre commande pour " . $Moneyw . "MAD";  
		}
		
		
		$url = 'https://fcm.googleapis.com/fcm/send';
		$fields =array(
			 'to' => $DriverToken,
			 'notification'=>array(
			 'title' => "$Title",
			 'body' => "$body",
			 "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($DriverToken,$OrderID,$FNamew,$LANGw,$Moneyw,$accessTokenw,$Pid)
	{

		if($LANGw=="AR"||$LANGw=="ar"){
			$Title = $FNamew . " في طريقه الي استلام";
			$body  = $FNamew . " قد قدم عرًضا لتوصيل طلبك بقيمة " . $Moneyw . "درهم مغربي"; 
		}else if($LANGw=="EN"||$LANGw=="en"){
			$Title = $FNamew . " is on their way to pick up your order";
			$body  = $FNamew . " has offered to deliver your order for " . $Moneyw . "MAD"; 
		}else if($LANGw=="FR"||$LANGw=="fr"){
			$Title = $FNamew . " est en route pour récupérer votre commande";
			$body  = $FNamew . " a proposé de livrer votre commande pour " . $Moneyw . "MAD";  
		}


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

        $fields = array(
            'message' => array(
                'token' => $DriverToken,
                'notification' => array(
                    'title' => $Title,
                    'body' => $body
                )
            )
        );

		$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);
?>