<?php
ini_set('display_errors', 'On');
error_reporting(E_ERROR);
include 'send_gcm.php';
include 'update_timestamp.php';
include 'insert_into_sync_table.php';

/*DEPRECATED Use version 2*/
/*The following code will add/upd/del data in SERVICE_TABLE. Insert data into SYNC_TABLE. And notify partner phones*/

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

// check for required fields
if (isset($_POST['email']) && isset($_POST['type']) && isset($_POST['source'])) {
	// 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 email and android id and source
	$email = $_POST['email'];
	$androidId = $_POST['androidId'];
	$source = $_POST['source'];
	
	//check that android id is not in sync table
	if($stmt = $mysqli->prepare("SELECT * FROM SYNC_TABLE WHERE ANDROID_ID = ?")){
		$stmt->bind_param("s", $androidId);
		$stmt->execute(); 
		$stmt->store_result();
    		$num_rows = $stmt->num_rows;
    		
    		//proceed only if android id does not exist
    		if($num_rows == 0){
    			$type = $_POST['type'];
    			$id = $_POST['_id'];
			$vid = $_POST['vehid'];
			$rec_type = $_POST['rec_type'];
			$serviceName = $_POST['serviceName'];
			$recurring = $_POST['recurring'];
			$dueMiles = $_POST['dueMiles'];
			$dueDays = $_POST['dueDays'];
			$lastOdo = $_POST['lastOdo'];
			$lastDate = $_POST['lastDate'];
			
			//get user id
			if($stmt = $mysqli->prepare("SELECT USER_ID FROM USER_ID WHERE EMAIL = ?")){
				$stmt->bind_param("s", $email);	
				$stmt->execute();
				$stmt->bind_result($temp_user_id);
				while($stmt->fetch()){
		    			$user_id = $temp_user_id;
		    		}
		    		
		    		//add data into table
		    		if(strcmp($type, "add") == 0){
		    			if($stmt = $mysqli->prepare("INSERT INTO SERVICE_TABLE(USER_ID, _ID, VEHID, TYPE, SERVICE_NAME, RECURRING, DUE_MILES, DUE_DAYS, LAST_ODO, LAST_DATE) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")){
		    				$stmt->bind_param("iisisididi", $user_id, $id, $vid, $rec_type, $serviceName, $recurring, $dueMiles, $dueDays, $lastOdo, $lastDate);
		    				$result = $stmt->execute();
		    				
		    				// successfully inserted into database
		    				if ($result) {
		    					//update sync table		    		
		    					if(insertIntoSyncTable($mysqli, $id, $type, $user_id, "SERVICE_TABLE", $androidId)){
		    						//get other reg ids of the same email
		    						$reg_id = getOtherRegIds($mysqli, $user_id, $androidId);		    						
		    						
		    						//send message to other phones belonging to same email
		    						sendGCMMessage($reg_id, "pull");
		    					}
		    					
		    					//update timestamp in Profile
		    					updateTimestamp($user_id);
		    					
		    					$response["success"] = 1;
							$response["message"] = "Success";
				
							// echoing JSON response
							echo json_encode($response);
		    				}
		    				//if failure due to unique constraint then move on
						else if($mysqli->errno===1062){
							$response["success"] = 1;
							$response["message"] = "Success";
				
							// echoing JSON response
							echo json_encode($response);
						}
		    			}	
		    		}
		    		//update log rec		    		
				else if(strcmp($type, "edit") == 0){
					if($stmt = $mysqli->prepare("UPDATE SERVICE_TABLE SET VEHID=?, TYPE=?, SERVICE_NAME=?, RECURRING=?, DUE_MILES=?, DUE_DAYS=?, LAST_ODO=?, LAST_DATE=? WHERE USER_ID=? and _ID=?")){
						$stmt->bind_param("sisididiii", $vid, $rec_type, $serviceName, $recurring, $dueMiles, $dueDays, $lastOdo, $lastDate, $user_id, $id);
						$result = $stmt->execute();
						
						// rec has been updated succesfully
		    				if($result){
		    					//update sync table		    		
		    					if(insertIntoSyncTable($mysqli, $id, $type, $user_id, "SERVICE_TABLE", $androidId)){
		    						//get other reg ids of the same email
		    						$reg_id = getOtherRegIds($mysqli, $user_id, $androidId);	    						
		    						
		    						//send message to other phones belonging to same email
		    						sendGCMMessage($reg_id, "pull");
		    					}
		    					
		    					//update timestamp in Profile
		    					updateTimestamp($user_id);
		    					
		    					$response["success"] = 1;
							$response["message"] = "Success";
				
							// echoing JSON response
							echo json_encode($response);
		    				}
					}
				}
				//delete log rec
				else if(strcmp($type, "del") == 0){
					//delete record
					$stmt = $mysqli->prepare("DELETE FROM SERVICE_TABLE WHERE USER_ID=? and _ID=?");
					$stmt->bind_param("ii", $user_id, $id);
					$result = $stmt->execute();
					
					// rec has been deleted succesfully
		    			if($result){
		    				//update sync table		    		
		    				if(insertIntoSyncTable($mysqli, $id, $type, $user_id, "SERVICE_TABLE", $androidId)){
		    					//get other reg ids of the same email
		    					$reg_id = getOtherRegIds($mysqli, $user_id, $androidId);		    						
		    					
		    					//send message to other phones belonging to same email
		    					sendGCMMessage($reg_id, "pull");
		    				}
		    				
		    				//update timestamp in Profile
		    				updateTimestamp($user_id);
		    				
		    				$response["success"] = 1;
						$response["message"] = "Success";
				
						// echoing JSON response
						echo json_encode($response);
		    			}
				}
			}
			
    		}
    		//else user's android id exists in the Sync table, inform him that data on his phone is out of sync				 			
		else{		
			//get reg_id
			if($stmt = $mysqli->prepare("SELECT REG_ID FROM PROFILE WHERE ANDROID_ID=?")){
				$stmt->bind_param("s", $androidId);	
				$stmt->execute();
				$stmt->bind_result($temp_reg_id);
				while($stmt->fetch()){
					$reg_id[] = $temp_reg_id;
				}
				
				//send message to user
				sendGCMMessage($reg_id, "out of sync");
			}
		}
		
		// Close the prepared statement.
    		if($stmt != null){
			$stmt->close(); 
	    	} 
	}
	
	//else send generic failure message
	if($response["success"] == 0){
		$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 get other reg ids
function getOtherRegIds($mysqli, $userID, $androidIDToIgnore){
	$sql = "";

	//if android id to ignore is null (called from web) then return all android_ids for that user id
	if(empty($androidIDToIgnore)){
		$sql = 	"SELECT REG_ID FROM PROFILE WHERE USER_ID = ?";
	}
	//else get android IDs for the same email id except the one from which this request has come
	else{
		$sql = "SELECT REG_ID FROM PROFILE WHERE USER_ID = ? AND ANDROID_ID!=?";
	}

	if($stmt = $mysqli->prepare($sql)){
		if(empty($androidIDToIgnore)){
			$stmt->bind_param("s", $userID);	
		}
		else{
			$stmt->bind_param("ss", $userID, $androidIDToIgnore);	
		}
		$stmt->execute();
		$stmt->bind_result($temp_reg_ids);
		while($stmt->fetch()){
			$reg_id[] = $temp_reg_ids;
		}
		
		// Close the prepared statement.
    		if($stmt != null){
			$stmt->close(); 
	    	} 

		return $reg_id;
	}
}

?>