<?php
// Backend for participation list (GET only)
// Returns athletes with bib, category, and final placement for a competition

include 'dbconnect.php';

header('Content-Type: application/json');
$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
	if (!isset($_GET['competitionCode'])) {
		echo json_encode(["success" => false, "error" => "Missing competitionCode parameter."]);
		exit;
	}
	$competitionCode = $_GET['competitionCode'];

	$query = "
		SELECT
			a.id,
			CONCAT(a.first_name, ' ', a.last_name) AS athlete,
			a.bib,
			a.event_code AS event_code,
			a.country AS country,
			COALESCE(c.name, '') AS category,
			a.final_placement AS placement,
			a.ranking_place AS ranking
		FROM athletes a
		LEFT JOIN categories c ON a.category_in_competition = c.code AND a.gender = c.gender
		WHERE a.competition_code = ?
		ORDER BY a.event_code ASC, a.final_placement ASC
	";
	$stmt = $conn->prepare($query);
	if (!$stmt) {
		echo json_encode(["success" => false, "error" => "Prepare failed: " . $conn->error]);
		exit;
	}
	$stmt->bind_param("s", $competitionCode);
	if (!$stmt->execute()) {
		echo json_encode(["success" => false, "error" => "Execute failed: " . $stmt->error]);
		exit;
	}

	$res = $stmt->get_result();

	// Group by event_code, then category
	$grouped = [];
	while ($row = $res->fetch_assoc()) {
		$event = $row['event_code'] ?: 'UN';
		$category = $row['category'] ?: 'Uncategorized';

		// Group by event_code, then category
		if (!isset($grouped[$event])) {
			$grouped[$event] = [];
		}
		if (!isset($grouped[$event][$category])) {
			$grouped[$event][$category] = [];
		}

		$grouped[$event][$category][] = [
			'athlete'   => $row['athlete'],
			'bib'       => is_null($row['bib']) ? null : intval($row['bib']),
			'country'   => $row['country'],
			'placement' => is_null($row['placement']) ? null : intval($row['placement']),
			'ranking'   => $row['ranking'],
		];
	}
	$stmt->close();

	echo json_encode([
		'success' => true,
		'events'  => $grouped
	]);
	exit;
}

// Unsupported method
echo json_encode(["success" => false, "error" => "Unsupported request method."]);
exit;
?>
