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

/*The following code will add data into the SYNC_TABLE for it to be pulled by partner phones*/

//function to insert into the sync table
function insertIntoSyncTable($mysqli, $rowID, $type, $userID, $table_name, $androidIDToIgnore){
	$sql = "";
	error_log("\nandroidIDToIgnore: ".$androidIDToIgnore, 3, "my-errors.log");
	//if android id to ignore is null (called from web) then return all android_ids for that user id
	if(empty($androidIDToIgnore)){
		$sql = 	"SELECT ANDROID_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 ANDROID_ID FROM PROFILE WHERE USER_ID = ? AND ANDROID_ID!=?";
		error_log("\nsql: ".$sql, 3, "my-errors.log");
	}

	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_android_ids);
		while($stmt->fetch()){
			$android_id[] = $temp_android_ids;
		}
		
		error_log("\nandroid ids found: ".count($android_id), 3, "my-errors.log");
		
		//if android id has any values
		if(count($android_id)>0){
			for($i=0; $i<count($android_id); $i++){
				$stmt = $mysqli->prepare("INSERT INTO SYNC_TABLE (TABLE_NAME, ROW_ID, TYPE, USER_ID, ANDROID_ID) VALUES(?, ?, ?, ?, ?)");
				$stmt->bind_param("sisis", $table_name, $rowID, $type, $userID, $android_id[$i]);
    				$result = $stmt->execute(); 
    				
    				//if type is del, the delete any older 'add' and 'edit' records for the same record
    				if($result && strcmp($type, "del")==0){
    					$stmt = $mysqli->prepare("DELETE FROM SYNC_TABLE WHERE TABLE_NAME=? AND ROW_ID=? AND TYPE IN (?,?) AND USER_ID=? AND ANDROID_ID=?");
					$stmt->bind_param("sissis", $table_name, $rowID, $add="add", $edit="edit", $userID, $android_id[$i]);
    					$result = $stmt->execute(); 
    				}
			}
			
			//if last result was success then return true
			if($result){
				// Close the prepared statement.
				if($stmt != null){
	    				$stmt->close(); 
	    			}
		    		
				return true;
			}
			//if failure due to unique constraint then also return true since we want the sync to take place
			else if($mysqli->errno===1062){
				// Close the prepared statement.
				if($stmt != null){
	    				$stmt->close(); 
	    			}
		    		
				return true;
			}
			else{
				// Close the prepared statement.
	    			if($stmt != null){
	    				$stmt->close(); 
	    			}
	    			
				return false;
			}
		}
		//no android ids found, so return false (since nothing inserted and no message to be sent)
		else{
			// Close the prepared statement.
			if($stmt != null){
	    			$stmt->close(); 
	    		}
	    		
			return false;
		}
	}
	else{
		return false;
	}		
}

?>