<?php

function generateSnakeSystemStartList(
	$athletesCount, 
	$maxGroupSize,
	$numGroups, 
	$round, 
	$previous_round_termination, 
	$total_athletes,
	$qualify_previous_round) {
		
	// Erzeuge ein Array von 1 bis $athletesCount
	
	if($qualify_previous_round != $athletesCount && $round != 1 && $previous_round_termination == 1)
	{
		// 1st athlete 1 bis $qualify_previous_round aus $round - 1
		// 2nd athlete 1 bis $athletesCount - $qualify_previous_round aus $round - 2
		$athletes1 = range(1, $qualify_previous_round);
		$athletes2 = range(1, $athletesCount - $qualify_previous_round);
		$athletes = array_merge($athletes1, $athletes2);
	}elseif($previous_round_termination == 0)
	{
		$athletes = range($total_athletes-$athletesCount+1, $total_athletes);
	}else
	{
		$athletes = range(1, $athletesCount);
	}
	$round--;

	// Berechne Anzahl der Gruppen
	if(!isset($numGroups))
	{
		$numGroups = ceil($athletesCount / $maxGroupSize);	
	}
	
	$groups = array_fill(0, $numGroups, []);

	$groupIndex = 0;
	$reverse = false;
	$round_origin = $round;
	$previous_athlete = 1;
	// Verteile die Athleten im Snake-System
	foreach ($athletes as $athleteId) {
		
		if($athleteId < $previous_athlete)
		{
			$round_origin--;
		}
		
		$groups[$groupIndex][] = $round_origin.",".$athleteId;

		if (!$reverse) {
			$groupIndex++;
			if ($groupIndex >= $numGroups) {
				$groupIndex = $numGroups - 1;
				$reverse = true;
			}
		} else {
			$groupIndex--;
			if ($groupIndex < 0) {
				$groupIndex = 0;
				$reverse = false;
			}
		}
		
		$previous_athlete = $athleteId;
	}

	// Drehe die Reihenfolge der Gruppen um
	$groups = array_reverse($groups);

	// Drehe die Reihenfolge der Athleten innerhalb jeder Gruppe um
	foreach ($groups as &$group) {
		$group = array_reverse($group);
	}
	unset($group);
	
	$previous_athlete = 1;
	// Füge jeder Gruppe eine "group" hinzu und wandle die Athleten in {position, athlete}-Objekte um
	$finalGroups = [];
	foreach ($groups as $i => $group) {
		$withPositions = [];
		foreach ($group as $pos => $athleteId) {
			$array_athlete = explode(",", $athleteId);
			$withPositions[] = [
				"position" => $pos + 1,
				"athlete" => $array_athlete[1],
				"origin" => $athleteId
			];
			$previous_athlete = $athleteId;
		}
		$finalGroups[] = [
			"group" => $i + 1,
			"athletes" => $withPositions
		];
	}

	return $finalGroups;
}

?>

