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

/* The following code will sync data received with all the friends of the sender*/

//array for JSON response
$response = array();

//get json string
$json = file_get_contents('php://input');

//get json array
$jsonArr = json_decode($json, true);
error_log("\nsync data v2  called", 3, "my-errors.log");
foreach($jsonArr as $key=>$data)
{
   error_log("\ncalled:-".$key."-".$data, 3, "my-errors.log"); 
}
// check for required fields
if (isset($jsonArr['email']) && isset($jsonArr['id']) && isset($jsonArr['vehid']) && isset($jsonArr['odo']) && isset($jsonArr['OT']) && isset($jsonArr['type']) && isset($jsonArr['serviceType']) && isset($jsonArr['action'])){
	
	//get action
	$action = $jsonArr['action'];
	
	//if action is add
	if(strcmp($action, 'add')==0 || strcmp($action, 'update')==0){
		$email = $jsonArr['email'];
		$name = $jsonArr['name'];
		$id = $jsonArr['id'];
		$vehid = $jsonArr['vehid'];
		$date = $jsonArr['date'];
		$odo = $jsonArr['odo'];
		$OT = $jsonArr['OT'];
		$qty = $jsonArr['qty'];
		$pfill = $jsonArr['pfill'];
		$cost = $jsonArr['cost'];
		$day = $jsonArr['day'];
		$month = $jsonArr['month'];
		$year = $jsonArr['year'];
		$octane = $jsonArr['octane'];
		$fuelBrand = $jsonArr['fuelBrand'];
		$fillStation = $jsonArr['fillStation'];
		$notes = $jsonArr['notes'];
		$type = $jsonArr['type'];
		$serviceType = $jsonArr['serviceType'];
		$mfill = $jsonArr['mfill'];	
	
		//if action is update
		if(strcmp($action, 'update')==0){		
			$oldOdo = $jsonArr['oldOdo'];			
			$oldServiceType = $jsonArr['oldServiceType'];
		}
	}
	elseif(strcmp($action, 'delete')==0){
		$email = $jsonArr['email'];
		$name = $jsonArr['name'];
		$id = $jsonArr['id'];
		$vehid = $jsonArr['vehid'];
		$odo = $jsonArr['odo'];
		$OT = $jsonArr['OT'];
		$type = $jsonArr['type'];
		$serviceType = $jsonArr['serviceType'];
	}
	
	// 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");
 
 	//API Key
	$api_key = 'AIzaSyBcrrQw9HFn3wnFPzsE7ogjpqsI_drfbj4';		
	
	//get friends reg ids
	$all_reg_ids = getRegIdsFriends($email, $mysqli);
	
	// Set other POST variables for GCM
	$url = 'https://fcm.googleapis.com/fcm/send';
	
	$headers = array("Authorization: key=$api_key", "Content-Type: application/json");
	error_log("\nsending to friend", 3, "my-errors.log");
	//if action is add
	if(strcmp($action, 'add')==0){
		$fields = array("content_available"=>true, "registration_ids" => $all_reg_ids, "data" => array("email"=>$email, "name"=>$name, "id"=>$id, "vehid"=>$vehid, "date"=>$date, "odo"=>$odo, "OT"=>$OT, "qty"=>$qty, "pfill"=>$pfill, "cost"=>$cost, "day"=>$day, "month"=>$month, "year"=>$year, "ocatne"=>$octane, "fuelBrand"=>$fuelBrand, "fillStation"=>$fillStation, "notes"=>$notes, "type"=>$type, "serviceType"=>$serviceType, "mfill"=>$mfill, "action"=>$action), "priority"=>"high");
	}
	//if action is update
	elseif(strcmp($action, 'update')==0){
		$fields = array("content_available"=>true, "registration_ids" => $all_reg_ids, "data" => array("email"=>$email, "name"=>$name, "id"=>$id, "vehid"=>$vehid, "date"=>$date, "odo"=>$odo, "OT"=>$OT, "qty"=>$qty, "pfill"=>$pfill, "cost"=>$cost, "day"=>$day, "month"=>$month, "year"=>$year, "ocatne"=>$octane, "fuelBrand"=>$fuelBrand, "fillStation"=>$fillStation, "notes"=>$notes, "type"=>$type, "serviceType"=>$serviceType, "mfill"=>$mfill, "action"=>$action, "oldOdo"=>$oldOdo, "oldServiceType"=>$oldServiceType), "priority"=>"high");
	}
	//if action is delete
	elseif(strcmp($action, 'delete')==0){
		$fields = array("content_available"=>true, "registration_ids" => $all_reg_ids, "data" => array("email"=>$email, "name"=>$name, "id"=>$id, "vehid"=>$vehid, "odo"=>$odo, "OT"=>$OT, "type"=>$type, "serviceType"=>$serviceType, "action"=>$action), "priority"=>"high");
	}
	
	//TODO DELETE
	if(strcmp($email, 'appsrackinc@gmail.com')==0){
	    error_log("\nregistration_ids: ".print_r($all_reg_ids, TRUE)." email: ".$email.' name: '.$name.' id: '.$id.' vehid: '.$vehid.' OT: '.$OT.' type: '.$type.' serviceType: '.$serviceType.' action: '.$action, 3, "my-errors.log");
	}
	
	// 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", $all_reg_ids[$i]);
					$stmt->execute(); 
					
					// Close the prepared statement.
					if($stmt != null){
				    		$stmt->close(); 
				    	} 
				    	
				    	mysqli_close($mysqli);
				}			
			}
			++$i;
		}
	}
	 
	// Close connection
	curl_close($ch);
	
	// successfully inserted into database
	$response["success"] = 1;
	$response["message"] = "Data sent";
	        		    		    	
	// echoing JSON response
	echo json_encode($response);  
	
	mysqli_close($mysqli); 	 		  
}
else{
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
 
    // echoing JSON response
    echo json_encode($response);
}

//function to get reg id's for friends
function getRegIdsFriends($email, $mysqli){
	//statment to fetch friends reg ids
	if($stmt = $mysqli->prepare("SELECT REG_ID FROM PROFILE WHERE USER_ID IN (SELECT USER_ID FROM USER_ID WHERE EMAIL IN (SELECT EMAIL_2 FROM FRIENDS WHERE EMAIL_1 = ? AND STATUS = 'confirmed'))")){
		// Bind a variable to the parameter as a string. 
    		$stmt->bind_param("s", $email);
    		
    		// Execute the statement.
	    	$stmt->execute();  
	    	
	    	//get rows for the friends if any
    		$stmt->bind_result($friends_reg_ids);
    		
    		while ($stmt->fetch()) {    		
    			$all_friends_reg_ids[] = $friends_reg_ids;			  					  			    			
		}
		
		//statement to fetch reg ids whose friends we are
		if($stmt = $mysqli->prepare("SELECT REG_ID FROM PROFILE WHERE USER_ID IN (SELECT USER_ID FROM USER_ID WHERE EMAIL IN (SELECT EMAIL_1 FROM FRIENDS WHERE EMAIL_2 = ? AND STATUS = 'confirmed'))")){
			// Bind a variable to the parameter as a string. 
	    		$stmt->bind_param("s", $email);
	    		
	    		// Execute the statement.
		    	$stmt->execute();  
		    	
		    	//get rows for the friends if any
	    		$stmt->bind_result($friends_reg_ids);
	    		
	    		while ($stmt->fetch()) {    		
	    			$all_friends_reg_ids[] = $friends_reg_ids;			  			
			}
		}
		else{
			$response["success"] = 0;
			$response["message"] = "Failed to fetch reg ids";
					 
			// echoing JSON response
			echo json_encode($response);
    		}
    		
    		// Close the prepared statement.
		$stmt->close(); 
    		
    		//return friends' reg ids
		return $all_friends_reg_ids;    		
	}
	else{
		$response["success"] = 0;
		$response["message"] = "Failed to fetch reg ids";
				 
		// echoing JSON response
		echo json_encode($response);
    }	
}

?>