<?php

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
	// 1) GET => List all athletes for this competition
	if (!isset($_GET['competitionCode'])) {
		echo json_encode(["success" => false, "error" => "Missing competitionCode parameter."]);
		exit;
	}
	$competitionCode = $_GET['competitionCode'];

	// Example: fetch id, first_name, last_name, bib from 'athletes' for this competition
	$query = "
		SELECT 
			id,
			CONCAT(first_name, ' ', last_name) AS full_name,
			bib,
			gender
		FROM athletes
		WHERE competition_code = ?
		ORDER BY gender, last_name 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;
	}

	$result = $stmt->get_result();
	$athletes = [];
	while ($row = $result->fetch_assoc()) {
		$athletes[] = [
			"id"        => intval($row['id']),
			"full_name" => $row['full_name'],
			"bib"       => is_null($row['bib']) ? null : intval($row['bib']),
			"gender" => $row['gender'],
		];
	}
	$stmt->close();

	echo json_encode([
		"success"   => true,
		"athletes"  => $athletes
	]);
	exit;

} elseif ($method === 'POST') {
	// 2) POST => Update a single athlete's bib number
	$data = json_decode(file_get_contents("php://input"), true);
	if (!$data) {
		echo json_encode(["success" => false, "error" => "Invalid or missing JSON body."]);
		exit;
	}

	// Check required fields
	if (!isset($data['athlete_id']) || !isset($data['bib'])) {
		echo json_encode(["success" => false, "error" => "Missing 'athlete_id' or 'bib' field."]);
		exit;
	}

	$athleteId = intval($data['athlete_id']);
	$bibValue  = intval($data['bib']);

	// 2A) Find the athlete's competition_code
	$compQuery = "
		SELECT competition_code
		FROM athletes
		WHERE id = ?
		LIMIT 1
	";
	$compStmt = $conn->prepare($compQuery);
	if (!$compStmt) {
		echo json_encode(["success" => false, "error" => "Prepare failed: " . $conn->error]);
		exit;
	}
	$compStmt->bind_param("i", $athleteId);
	if (!$compStmt->execute()) {
		echo json_encode(["success" => false, "error" => "Execute failed: " . $compStmt->error]);
		exit;
	}
	$compRes = $compStmt->get_result();
	$compRow = $compRes->fetch_assoc();
	$compStmt->close();

	if (!$compRow || empty($compRow['competition_code'])) {
		echo json_encode(["success" => false, "error" => "No athlete found or missing competition_code."]);
		exit;
	}

	$competitionCode = $compRow['competition_code'];

	// 2B) Check if the same bib is already used by a different athlete in this competition
	$checkQuery = "
		SELECT id
		FROM athletes
		WHERE competition_code = ?
		  AND bib = ?
		  AND id <> ?
		LIMIT 1
	";
	$checkStmt = $conn->prepare($checkQuery);
	if (!$checkStmt) {
		echo json_encode(["success" => false, "error" => "Prepare failed: " . $conn->error]);
		exit;
	}
	$checkStmt->bind_param("sii", $competitionCode, $bibValue, $athleteId);
	if (!$checkStmt->execute()) {
		echo json_encode(["success" => false, "error" => "Execute failed: " . $checkStmt->error]);
		exit;
	}
	$checkRes = $checkStmt->get_result();
	$checkRow = $checkRes->fetch_assoc();
	$checkStmt->close();

	if ($checkRow) {
		// means there's another athlete with the same bib in the same competition
		echo json_encode([
			"success" => false,
			"error"   => "This bib number is already in use by another athlete."
		]);
		exit;
	}

	// 2C) If no conflict, update
	$updateQuery = "
		UPDATE athletes 
		SET bib = ? 
		WHERE id = ?
		LIMIT 1
	";
	$stmt = $conn->prepare($updateQuery);
	if (!$stmt) {
		echo json_encode(["success" => false, "error" => "Prepare failed: " . $conn->error]);
		exit;
	}
	$stmt->bind_param("ii", $bibValue, $athleteId);
	if (!$stmt->execute()) {
		echo json_encode(["success" => false, "error" => "Execute failed: " . $stmt->error]);
		exit;
	}
	$stmt->close();

	// Return success
	echo json_encode(["success" => true, "message" => "Bib number updated successfully."]);
	exit;

} else {
	// If not GET or POST
	echo json_encode(["success" => false, "error" => "Unsupported request method."]);
	exit;
}

?>