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

/* The following code updates record in the FRIENDS tabe with STATUS as 'CONFIRMED' and sends an update to the request sender */

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

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

//get json array
$jsonArr = json_decode($json, true);

// check for required fields
if (isset($jsonArr['email1']) && isset($jsonArr['name1']) && isset($jsonArr['email2']) && isset($jsonArr['name2'])){
	$email1 = $jsonArr['email1'];
	$name1 = $jsonArr['name1'];
	$email2 = $jsonArr['email2'];
	$name2 = $jsonArr['name2'];

	// 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 requestors reg id
	if($stmt = $mysqli->prepare("SELECT REG_ID FROM PROFILE WHERE USER_ID = (SELECT USER_ID FROM USER_ID WHERE EMAIL LIKE ?)")){
		
		// Bind a variable to the parameter as a string. 
		$stmt->bind_param("s", $email1);    		    	
		    		
		// Execute the statement.
		$stmt->execute();
			    	
		//get rows for the friend if any		    	
		$stmt->bind_result($reg_id);
				
		while ($stmt->fetch()){ 
			$friend_reg_id[] = $reg_id;
		}
				
		if(isset($friend_reg_id)){
				
		    	//send request 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("content_available"=>true, "registration_ids" => $friend_reg_id, "data" => array("email"=>$email2, "name"=>$name2, "type"=>'add friend', "action"=>'confirm'));
					
			// 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);
					
			//update data in FRIENDS
		    	if($stmt = $mysqli->prepare("UPDATE FRIENDS SET STATUS = 'confirmed' WHERE EMAIL_1=? AND EMAIL_2=?")){
		    		// Bind a variable to the parameter as a string. 
				$stmt->bind_param("ss", $email1, $email2);
				    		
				// Execute the statement.
				$result = $stmt->execute();
					    	
				// row has been updated succesfully
				if($result){ 
					//return friends list
					$response["success"] = 1;
										 
					// echoing JSON response
					echo json_encode($response);
				}
				//else return error
				else{    					    		
					$response["success"] = 0;
					$response["message"] = mysqli_error($mysqli);
							 
					// echoing JSON response
					echo json_encode($response);
				}				    						    		
		    	}
			else{
				$response["success"] = 0;
				$response["message"] = "Failed to update data";
								 
				// echoing JSON response
				echo json_encode($response);
			}  										
		}	
		else{
		    	$response["success"] = 0;
			$response["message"] = "No reg id found";
								 
			// echoing JSON response
			echo json_encode($response);
		}
				
		// Close the prepared statement.
		$stmt->close();
	}
	else{
		$response["success"] = 0;
		$response["message"] = "Failed to update data";
						 
		// 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);
}


?>