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

/*DEPRECATED Use version 3*/
/* The following code will create/update data in the PROFILE/USER_ID table 
the value returned will include a message that states if the user has been 'created'
or is 'existing' and the users friends if he has any*/

// array for JSON response
$response = array();
$response["success"] = 0;
$response["message"] = "Failed";

// check for required fields
if (isset($_POST['email']) && isset($_POST['androidId']) && isset($_POST['personName']) && isset($_POST['regId']) && $_POST['email']!="") {
	$email = $_POST['email'];
	$androidId = $_POST['androidId'];
	$name = $_POST['personName'];
	$regId = $_POST['regId'];
	
	// 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");
    	
    	//check if android id already exists
    	if($stmt = $mysqli->prepare("SELECT USER_ID, NAME, REG_ID FROM PROFILE WHERE ANDROID_ID = ?")){
    	
    		// Bind a variable to the parameter as a string. 
    		$stmt->bind_param("s", $androidId);
    		
    		// Execute the statement.
	    	$stmt->execute();  
	    	
	    	// store result
    		$stmt->store_result();
    		    		
		//get number of rows returned
    		$num_rows = $stmt->num_rows;        				    		
    		
    		//if android id already exists
    		if($num_rows > 0){
    			//get email and name associated with the android_id
    			$stmt->bind_result($temp_user_id, $temp_name, $temp_reg_id);
    			
    			while($stmt->fetch()){
    				$curr_user_id = $temp_user_id;
    				$curr_name = $temp_name;
    				$curr_reg_id = $temp_reg_id;
    			}
    			
    			//get email from user_id
    			if($stmt = $mysqli->prepare("SELECT EMAIL FROM USER_ID WHERE USER_ID = ?")){
    				$stmt->bind_param("s", $curr_user_id);
    				$stmt->execute(); 
    				$stmt->bind_result($temp_email);
    				while($stmt->fetch()){
    					$curr_email = $temp_email;
    				}
    				
    				//if email is different from what user already had for that android_id
    				if(strcmp($curr_email, $email) != 0) {
    					//delete the record
    					if($stmt = $mysqli->prepare("DELETE FROM PROFILE WHERE ANDROID_ID = ?")){
    						// Bind a variable to the parameter as a string. 
			    			$stmt->bind_param("s", $androidId);
				    		$stmt->execute();  
				    	
				    		//insert new record 
				    		insertRec($mysqli, $email, $name, $regId, $androidId);
    					}    				   			
    				}
    				//else email is the same
    				else{
    					//check if name or reg_id is different
    					if(strcmp($curr_name, $name) != 0 || strcmp($curr_reg_id, $regId) != 0) {
    						//update email and name
    						if($stmt = $mysqli->prepare("UPDATE PROFILE SET NAME = ?, REG_ID = ? WHERE ANDROID_ID = ?")){
    							$stmt->bind_param("sss", $name, $regId, $androidId);
    							$result = $stmt->execute();
    						
    							// name/reg_id has been updated succesfully
    							if($result){
    								//return friends list
		    						getFriends($email, $mysqli);
    							}    						
    						}    					
    					}
    					//else email, name,reg_id all the same
    					else{
    						//return friends list
    						getFriends($email, $mysqli);
    					}
    				}
    			}    			    		   			    			
    		}    	
    		//if no rows exist for the android id then insert the record
    		else {
    			// inserting a new row 
    			insertRec($mysqli, $email, $name, $regId, $androidId);
    		}	
    		
    		// Close the prepared statement.
    		$stmt->close();   	
	}
	
	//else send generic failure message
	if($response["success"] != 1){
		$response["success"] = 0;
		$response["message"] = "Failed";
						 
		// 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 insert new record into user_id and PROFILE table
function insertRec($mysqli, $email, $name, $regId, $androidId){
	
	//check if email_id already exists
	if($stmt = $mysqli->prepare("SELECT USER_ID FROM USER_ID WHERE EMAIL = ? LIMIT 1")){

		// Bind a variable to the parameter as a string. 
    		$stmt->bind_param("s", $email);
	
    		// Execute the statement.
	    	$stmt->execute();  
	    	
	    	//get number of rows returned
	    	$stmt->store_result();
    		$num_rows = $stmt->num_rows; 
    		
    		//check if user id exists
    		if($num_rows == 1){
	    		//get rows for the friends if any
    			$stmt->bind_result($retrived_user_id);
    			while($stmt->fetch()){
    				$user_id = $retrived_user_id;	
    			}
    			
    			//insert rec in only profile
    			insertRecInProfile($mysqli, $user_id, $name, $regId, $androidId, $email);
    		}
    		//else user id does not exist
    		else{
    			//get max user id
    			if($stmt = $mysqli->prepare("SELECT MAX(USER_ID) FROM USER_ID")){
				// Execute the statement.
	    			$stmt->execute();  
	    	
			    	//get rows max user id
		    		$stmt->bind_result($max_user_id);
		    		while($stmt->fetch()){
	    				$user_id = $max_user_id+1;
	    			}
    				
	    			if($stmt = $mysqli->prepare("INSERT INTO USER_ID(USER_ID, EMAIL) VALUES(?, ?)")){
    					$stmt->bind_param("ss", $user_id, $email);
    					$result = $stmt->execute(); 
    					
    					// successfully inserted into database
    					if ($result) {
    						//insert into profile table
    						insertRecInProfile($mysqli, $user_id, $name, $regId, $androidId, $email);
    					}    					
	    			}	    				
    			}
    		}  
    		
    		// Close the prepared statement.
	    	if($stmt != null){
			$stmt->close(); 
		}
	}	
}

//function to insert record into profile table
function insertRecInProfile($mysqli, $user_id, $name, $reg_id, $android_id, $email){
	
	//insert new record
    	if($stmt = $mysqli->prepare("INSERT INTO PROFILE(USER_ID, NAME, REG_ID, ANDROID_ID) VALUES(?, ?, ?, ?)")){
    		// Bind the variables to the parameter as strings. 
    		$stmt->bind_param("ssss", $user_id, $name, $reg_id, $android_id);
    			
    		// Execute the statement.
    		$result = $stmt->execute(); 				    			    			
    				
    		// successfully inserted into database
    		if ($result) {
    			//return friends list
    			getFriends($email, $mysqli);
    		}    
    		
    		// Close the prepared statement.
    		if($stmt != null){
			$stmt->close(); 
		}		
    	}    	
}

//function to return friends of email in argument
function getFriends($email, $mysqli){
	//declare global variables
	global $response;

	//statment to fetch friends
	if($stmt = $mysqli->prepare("SELECT EMAIL_2, NAME_2, STATUS FROM FRIENDS WHERE EMAIL_1 = ?")){
		// 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_email, $friends_name, $status);
    		
    		while ($stmt->fetch()) {    		
    			$all_friends_emails[] = $friends_email;			  			
    			$all_friends_names[] = $friends_name;	
    			
    			if(strcmp($status, 'requested') == 0){
    				$all_status[] = 'request sent';
    			}
    			else{
    				$all_status[] = $status;
    			}		  			    			
		}
		
		//statement to fetch emails whose friends we are
		if($stmt = $mysqli->prepare("SELECT EMAIL_1, NAME_1, STATUS FROM FRIENDS WHERE EMAIL_2 = ?")){
			// 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_email, $friends_name, $status);
	    		
	    		while ($stmt->fetch()) {    		
	    			$all_friends_emails[] = $friends_email;			  			
	    			$all_friends_names[] = $friends_name;	
	    			
	    			if(strcmp($status, 'requested') == 0){
	    				$all_status[] = 'request received';
		    		}
		    		else{
		    			$all_status[] = $status;
		    		}		  			    			
			}
		}		
    		
    		//check if data on cloud needs to be downloaded    	
    		$sync_ts[] = fetchTimestamp($email, $mysqli);
    		
    		//return friends' names
    		if((isset($all_friends_emails) && !is_null($all_friends_emails)) || (isset($all_friends_names) && !is_null($all_friends_names))){
    			$response["success"] = 1;
			$response["message"] = "Success";
			
			echo json_encode(array('all_friends_emails'=>$all_friends_emails, 'all_friends_names'=>$all_friends_names, 'all_status'=>$all_status, 'sync_ts'=>$sync_ts));
		}
		else{			
			$response["success"] = 1;
			$response["message"] = "Success";
			
			//send back that no friends were found
			$all_friends_emails[] = "no friends found";
			
			echo json_encode(array('all_friends_emails'=>$all_friends_emails, 'sync_ts'=>$sync_ts));
		}
    		
    		// Close the prepared statement.
    		if($stmt != null){
			$stmt->close(); 
		}
	}	
}

//function to fetch timestamp
function fetchTimestamp($email, $mysqli){
	$stmt = $mysqli->prepare("SELECT TIMESTAMP FROM USER_ID WHERE EMAIL = ?");
	$stmt->bind_param("s", $email);
	$stmt->execute();  
	$stmt->bind_result($temp_ts);
	while ($stmt->fetch()) {
		$ts = $temp_ts;
	}
	
	// Close the prepared statement.
    	if($stmt != null){
		$stmt->close(); 
	}
	
	return $ts;
}

?>