<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require ('../credentials.php');
$con=mysqli_connect(HOST, USERNAME, PASSWORD, DBNAME)or die("cannot connect"); 

define('GOOGLE_API_KEY', 'AAAAt2LXVII:APA91bEBop0-4r6XcEmc6rIUyzpKHhxP2vLRE15v5gq9x6AFS7s1RnGmPZTMrm0xEvur_XjIMoWqXqmJXAhsjm5RQpMAZtzhUVgITEsyaixTVYQHAUXIIgRx0TPv8TSUkcb9bZTw1rvs');//Replace with your Key


$pushStatus = '0';
$dayQuery="";
$month = $_POST['month'];
$day = $_POST['day'];

if($day=='ALL'){}
else{
$dayQuery=" and day ='$day'";
}

if(isset($_POST['month'])) {
	$gcmRegIds = array();
	$users_affected = array();
	$sql = "SELECT gcm_device_token FROM student where month ='$month'".$dayQuery." union SELECT gcm_device_token FROM staff where month ='$month'".$dayQuery ;
    	
    
    $result = mysqli_query($con,$sql);
	
	$sql2 ="";
	
	while($row = mysqli_fetch_assoc($result)){
		
		array_push($gcmRegIds, $row["gcm_device_token"]);
	}
	
    $title = $_REQUEST['title'];
	 $body = $_REQUEST['body'];
	  $image = $_REQUEST['image'];
	  $dateSent= date("Y-m-d h:i:sa");
    if(isset($gcmRegIds) && isset($title)) {
        $message = array('title' => $title,'body'=>$body,'image'=>$image,'date'=>$dateSent);
        $pushStatus = sendPushNotification($gcmRegIds, $message);
        echo $pushStatus ;
    }   
    
}

function sendPushNotification($registration_ids, $message) {
            // Set POST variables
        $url = 'https://android.googleapis.com/gcm/send';
		$fields = array(
            'registration_ids' => $registration_ids,
            'data' => $message,
        );
        $headers = array(
            'Authorization: key=' . GOOGLE_API_KEY,
            'Content-Type: application/json'
        );
        // 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));
		curl_setopt($ch, CURLOPT_SSLVERSION,3); // Apparently 2 or 3
        // Execute post
        $result = curl_exec($ch);
        if ($result === FALSE) {
            die('Curl failed: ' . curl_error($ch));
        }
        // Close connection
        curl_close($ch);
		return $result;
}
?>
