<?php
ini_set('display_errors', 'On');
error_reporting(E_ERROR);

/*The following code sends a FCM message using server key of 'API Project'*/

//function to send type to reg_id(s)
function sendGCMMessage($reg_id, $type){
	$api_key = 'AIzaSyBcrrQw9HFn3wnFPzsE7ogjpqsI_drfbj4';	
	$url = 'https://fcm.googleapis.com/fcm/send';
	$headers = array("Authorization: key=$api_key", "Content-Type: application/json");
	$fields = array("content_available"=>true, "registration_ids"=>$reg_id, "data"=>array("type"=>$type), "priority"=>"high");
	
	// Open connection
	$ch = curl_init();
				 
	// Set the url, number of POST vars, POST data
	curl_setopt($ch, CURLOPT_URL, $url);	 
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	
	// Disabling SSL Certificate support temporarly
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
				 
	curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
				
	// Execute post
	$result = curl_exec($ch);		

	if ($result === FALSE) {			
		die('Curl failed: ' . curl_error($ch));		
	}
	//else result was a success
	else{
		//check if any not registered token in there
		$json_res = json_decode($result, true);
		$res = $json_res['results'];
		
		//set counter for reg_id array
		$i = 0;
		
		//loop through all results
		foreach ($res as $row) {			
			foreach ($row as $key => $value) {
				if(strcmp($value, "NotRegistered")==0){
					// include db config class
					require_once __DIR__ . '/db_config.php';
	
					// connecting to db
				    	$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
				    	
					//delete from PROFILE table
					$stmt = $mysqli->prepare("DELETE FROM PROFILE WHERE REG_ID = ?");
					$stmt->bind_param("s", $reg_id[$i]);
					$stmt->execute(); 
					
					// Close the prepared statement.
					if($stmt != null){
				    		$stmt->close(); 
				    	} 
				    	
				    	mysqli_close($mysqli);
				}			
			}
			++$i;
		}
	}
				 
	// Close connection
	curl_close($ch);
}

?>