<?php

function mp_coord_already_exist(&$coordinates, &$locations) {
	foreach ($locations as $location) {
		if ($location->coordinates->lat == $coordinates->lat)
			if ($location->coordinates->lng == $coordinates->lng)
				return $location;
	}
	return null;
}

function mp_sort_n_insert(&$event, &$locations) {
	$coordinates = $event->location->coordinates;
	if ($coordinates == null)
		return;

	$already_exist = mp_coord_already_exist($coordinates, $locations);
	if ($already_exist) {
		// add index to the event
		$index = $already_exist->index;
		$event->index = $index;
		// add event to events[]
		array_push($already_exist->events, $event);
	}
	else {
		// create new location object
		$location = (object)[];
		$location->events = [];

		// add index to the location and event
		$index = count($locations);
		$location->index = $index;
		$event->index = $index;
		// add coordinates to the location
		$location->coordinates = $coordinates;
		// add first event to events[]
		array_push($location->events, $event);
		// add this location to locations[]
		array_push($locations, $location);
	}
}

function mp_sort_events(&$events) {
	$locations = [];
	
	foreach ($events as $event) {
		mp_sort_n_insert($event, $locations);
	};

	return $locations;
}

/*

	locations =	[
					{
						index      : x
						coordinates: {}
						events     : [{}, ...]
					},
					...
				]

*/

?>
