<?php

// Function to include the step into the ladder seeding
function moveArrayItem(array $array, int $oldIndex, int $newIndex): array
{
	
	// If $oldIndex invalid or $newIndex out of range, do nothing
	if (!isset($array[$oldIndex]) || $newIndex < 0) {
		return $array;
	}

	$item = $array[$oldIndex];
	unset($array[$oldIndex]);
	$array = array_values($array);

	array_splice($array, $newIndex, 0, [$item]);
	return $array;
}


// 1. Function to create athletes seeding as step-ladder logic
function gatherStepLadderAthletes(
	mysqli $conn,
	int $heatsystem,
	int $athletes,
	int $round
) {
	$sql = "
		SELECT qualify, termination, round
		FROM heatsystem
		WHERE heatsystem=?
		  AND athletes=?
		  AND round <= ?
		ORDER BY round ASC
	";
	$stmt = $conn->prepare($sql);
	if (!$stmt) {
		return ["error"=>"Cannot prepare:".$conn->error];
	}
	$stmt->bind_param("iii", $heatsystem, $athletes, $round);
	$stmt->execute();
	$res = $stmt->get_result();
	
	$all_qualify = [];
	$prev_termination = 0;
	$prev_qualify = 0;
	$park_athletes = 0;
	while ($row = $res->fetch_assoc()) {
		if($row['round'] == 1)
		{
			$all_qualify[] = $athletes;
		}elseif($prev_termination != 0)
		{
			$all_qualify[] = $prev_termination;
		}else
		{
			$all_qualify[] = $prev_qualify + $park_athletes;
			$park_athletes = 0;
		}
		
		if($row['termination'] == 0)
		{
			$prev_termination = $athletes - $row['qualify'];
			$park_athletes = $row['qualify'];
		}else
		{
			$prev_termination = 0;
		}
		$prev_qualify = $row['qualify'];
	}
	$stmt->close();
	
	$total_athletes = [];
	$seeding_round = $round - 1;
	while($seeding_round >= 1)
	{
		$seeding_athletes = [];
		// 1) Query DB
		$sql = "
			SELECT
				heatsystem,
				athletes AS athletes,
				groups AS groups,
				round AS round, 
				capacity AS capacity,
				qualify AS qualify,
				termination AS termination
			FROM heatsystem
			WHERE heatsystem = ? AND athletes = ? AND round = ?
			LIMIT 1
		";
		$stmt = $conn->prepare($sql);
		if (!$stmt) {
			return ["error" => "Failed to prepare statement: " . $conn->error];
		}
		$stmt->bind_param("iii", $heatsystem, $athletes, $seeding_round);
		$stmt->execute();
		$res = $stmt->get_result();
		$row = $res->fetch_assoc();
		$stmt->close();
		
		$qualify = (int)$row['qualify'];
		$numGroups = (int)$row['groups'];
		$termination = (int)$row['termination'];
		
		if($termination == 0 && $seeding_round+1 == $round)
		{
			$num_start = $qualify + 1;
			for ($id = $num_start; $id <= $athletes; $id++) {
				$seeding_athletes[] = "$seeding_round,$id";
			}
		}else
		{
			$num_start = 1;
			for ($id = $num_start; $id <= $qualify; $id++) {
				$seeding_athletes[] = "$seeding_round,$id";
			}
		}
				


		// 3) "Move" each athlete
		$iteration = 1;
		for ($i = $numGroups; $i < count($seeding_athletes); $i += $numGroups) {
			if ($iteration === $numGroups) {
				$iteration = 0;
			}
			for ($m = 1; $m <= $iteration; $m++) {
				$s = $i + $numGroups - 1;
				$seeding_athletes = moveArrayItem($seeding_athletes, $i, $s);
			}
			$iteration++;
		}
		
		$total_athletes = array_merge($seeding_athletes, $total_athletes);
		if($all_qualify[$seeding_round] == count($seeding_athletes))
		{
			$seeding_round = 1;
		}
		$seeding_round --;
	}

	return $total_athletes;  // a flat array of "round,ID" strings
}


// Function to build the groups based on the athletes seeding
function buildBracket(
	mysqli $conn,
	int $groups,
	array $athleteStrings,
	int $capacity
): array 
{
	$termination = 1;
	$active_groups = $groups;
	$athletes = $athleteStrings;
	$maxGroupSize = $capacity;
	// If $active_groups not valid, recalc it
	if ($active_groups < 1) {
		$active_groups = ceil($athletesCount / $maxGroupSize);
	}

	// Prepare empty bracket
	$groups = array_fill(0, $active_groups, []);

	// offset
	$startGroup   = max(0, $termination - 1);
	// e.g. we can do $round_origin = $active_round - 1; or just $active_round
	// depends on your bracket logic
	$athleteIndex = 0;

	// Fill groups in non-shifting pattern
	for ($rowIndex = 0; $rowIndex < $maxGroupSize; $rowIndex++) {
		for ($g = 0; $g < $active_groups; $g++) {
			$groupIndex = ($startGroup + $g) % $active_groups;
			// place only up to $athletesCount 
			if ($athleteIndex < count($athletes) && $athleteIndex < count($athletes)) {
				$groups[$groupIndex][] = $athletes[$athleteIndex];
				$athleteIndex++;
			}
		}
	}

	// Reverse the groups array
	$groups = array_reverse($groups);

	// Reverse each group's internal order
	foreach ($groups as &$gr) {
		$gr = array_reverse($gr);
	}
	unset($gr);

	// Build final bracket
	$finalGroups = [];
	foreach ($groups as $i => $arr) {
		$withPositions = [];
		foreach ($arr as $pos => $val) {
			// e.g. "2,4"
			if (is_string($val) && strpos($val, ",") !== false) {
				list($rVal, $athNum) = explode(",", $val);
			} else {
				// fallback
				$rVal   = "???";
				$athNum = (string)$val;
			}
			$withPositions[] = [
				"position" => $pos + 1,
				"athlete"  => $athNum,
				"origin"   => $val
			];
		}
		$finalGroups[] = [
			"group"    => $i + 1,
			"athletes" => $withPositions
		];
	}

	return $finalGroups;
}


// Complete function to generate the athletes return
function generateStepLadderStartList(
	mysqli $conn,
	int $schedule_id
): array {
	
	// 1) Query DB
	$sql = "
		SELECT
			s.id,
			h.heatsystem AS heatsystem,
			h.athletes AS athletes,
			h.groups AS groups,
			h.round AS round, 
			h.capacity AS capacity,
			h.qualify AS qualify,
			h.termination AS termination
		FROM schedule s
		JOIN heatsystem h ON s.heatsystem = h.id
		WHERE s.id = ?
		LIMIT 1
	";
	$stmt = $conn->prepare($sql);
	if (!$stmt) {
		return ["error" => "Failed to prepare statement: " . $conn->error];
	}
	$stmt->bind_param("i", $schedule_id);
	$stmt->execute();
	$res = $stmt->get_result();
	$row = $res->fetch_assoc();
	$stmt->close();
	
	$heatsystem = (int)$row['heatsystem'];
	$athletes = (int)$row['athletes'];
	$round = (int)$row['round'];
	$groups = (int)$row['groups'];
	$capacity = (int)$row['capacity'];

	
	// A) Gather the athlete array
	$athleteStrings = gatherStepLadderAthletes(
		$conn,
		$heatsystem,
		$athletes,
		$round
	);
	if (isset($athleteStrings['error'])) {
		return $athleteStrings; // pass the error up
	}

	// C) Build bracket
	$final = buildBracket(
		$conn,
		$groups,
		$athleteStrings,
		$capacity
	);

	return $final;
}






// 2) Example usage of the function
// Let's say we have 12 athletes, max 4 per group, 3 groups, round 2, etc.:
include('dbconnect.php');
$schedule_id = $_GET['schedule'];

// Call the function
$result = generateStepLadderStartList(
	$conn,
	$schedule_id
);

echo "<pre>";
print_r($result);
echo "</pre>";
?>