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

/* THIS FILE IS DEPRECATED AFTER DATA IS STORED IN DB*/
/* The following code will save the full sync file in a particular folder and send a notification to destination with the path */

if (isset($_POST['email']) && isset($_POST['androidId'])){
	//get email of syncer	
	$email = $_POST['email'];
	$androidId = $_POST['androidId'];
	
	//set save path of file
	$file_path = "../SyncZipFiles/";
	$file_name = basename( $_FILES['zip_file']['name']);
	$file_path = $file_path . $file_name; 
	
	//move file to be synced to save path
	if(strcmp($file_name, ".zip")!=0 && move_uploaded_file($_FILES['zip_file']['tmp_name'], $file_path)){	
		
		// include db config class
		require_once __DIR__ . '/db_config.php';
	
		// connecting to db
	    	$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
	    	mysqli_set_charset($mysqli, "utf8");
		
		//get reg id of partner phone
		if($stmt = $mysqli->prepare("SELECT REG_ID FROM PROFILE WHERE USER_ID = (SELECT USER_ID FROM USER_ID WHERE EMAIL = ?) AND ANDROID_ID != ?")){
				
			// Bind a variable to the parameter as a string. 
	    		$stmt->bind_param("ss", $email, $androidId);
	    		
	    		// Execute the statement.
	    		$stmt->execute();  
	    	
		    	//get rows for the friend if any		    	
			$stmt->bind_result($reg_id);
		
			while ($stmt->fetch()){ 							
				$other_reg_ids[] = $reg_id;
			}
		
			if(isset($other_reg_ids)){							
				//send notification to friend
				//API Key
				$api_key = 'AIzaSyAXzbgOWcrJ4WDZLLAnlnma0XzVmh76Q2s';	
				
				// Set other POST variables for GCM
				$url = 'https://android.googleapis.com/gcm/send';
		
				$headers = array("Authorization: key=$api_key", "Content-Type: application/json");
								
				$fields = array("registration_ids" => $other_reg_ids, "data" => array("email"=>$email, "cloudSyncTS"=>filemtime ($file_path), "type"=>'cloud sync', "action"=>'pull'));
				
				// 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));
				}
				
				// Close connection
				curl_close($ch);
			}	
			
			// Close the prepared statement.
		    	$stmt->close(); 	
		}
	    	
	    	mysqli_close($mysqli); 
	}
}
else{
    echo "Required field(s) is missing"; 
}
?>