<?php

function generateRunsFromJson($conn, $jsonData){
	// Die JSON-Daten dekodieren
	$data = $jsonData;

	// Überprüfen, ob die Dekodierung erfolgreich war
	if (!$data || !$data['success']) {
		$message = "Ungültige oder erfolglose JSON-Daten.\n";
		return;
	}

	// 1) Prepare queries

	// We'll select a row by schedule, group, run, order (ignoring origin)
	$checkRunQuery = "
		SELECT id, origin
		FROM runs
		WHERE schedule = ?
		  AND `group` = ?
		  AND `run` = ?
		  AND `order` = ?
		LIMIT 1
	";

	// If no row found, we INSERT
	$insertRunQuery = "
		INSERT INTO runs (
			schedule, `group`, `run`, `order`,
			athlete, `status`, origin,
			real_time, timestamp
		)
		VALUES (
			?, ?, ?, ?,
			?, ?, ?,
			NULL, CURRENT_TIMESTAMP
		)
	";

	// If a row is found but origin is different, we UPDATE just the origin
	$updateRunQuery = "
		UPDATE runs
		SET origin = ?
		WHERE id = ?
	";

	$checkStmt  = $conn->prepare($checkRunQuery);
	$insertStmt = $conn->prepare($insertRunQuery);
	$updateStmt = $conn->prepare($updateRunQuery);

	if (!$checkStmt || !$insertStmt || !$updateStmt) {
		$message = "Fehler beim Vorbereiten der SQL-Anweisungen: (" . $conn->errno . ") " . $conn->error . "\n";
		return;
	}

	// 2) Iterate through each competition
	foreach ($data['data'] as $competition) {
		$comp      = $competition['comp'];      // optional usage
		$event     = $competition['event'];     // optional usage
		$category  = $competition['category'];  // optional usage

		// 3) Iterate through each round
		foreach ($competition['rounds'] as $round) {
			$roundNumber = $round['round'];

			// 4) Iterate through each schedule in the round
			foreach ($round['schedules'] as $schedule) {
				$scheduleId       = $schedule['schedule_id'];
				$heatsystemId     = $schedule['heatsystem_id'];
				$heatsystemDetail = $schedule['heatsystem_details'];

				$numRuns = $heatsystemDetail['runs'];
				$groups  = $heatsystemDetail['groups'];

				// 5) For each group
				foreach ($groups as $group) {
					$groupNumber = $group['group'];

					// We'll have runNumber from 1..numRuns
					for ($runNumber = 1; $runNumber <= $numRuns; $runNumber++) {

						// We track position in each run
						$position = 1;

						// 6) For each athlete in that group
						foreach ($group['athletes'] as $athlete) {
							$athleteId = 0; // Kann live während des Events gesetzt werden
							$origin    = $athlete['origin'];

							// Optional check: if "origin" doesn't have a comma => skip
							$originParts = explode(",", $origin);
							if (count($originParts) < 2) {
								$message = "Ungültiges Origin-Format: '$origin'\n";
								// skip this athlete
								$position++;
								continue;
							}

							$status = 0; // Standardstatus

							// ---------------------------------
							// 7) Check if a run row exists
							//    ignoring 'origin'
							// ---------------------------------
							if (!$checkStmt->bind_param("iiii", $scheduleId, $groupNumber, $runNumber, $position)) {
								$message = "Bind Param Fehler für Check: (" . $checkStmt->errno . ") " . $checkStmt->error . "\n";
								$position++;
								continue;
							}

							$checkStmt->execute();
							$checkResult = $checkStmt->get_result();

							if ($checkResult->num_rows > 0) {
								// => A row for (schedule, group, run, order=position) already exists
								$row       = $checkResult->fetch_assoc();
								$existingId      = $row['id'];
								$existingOrigin  = $row['origin'];

								// If origin is different => update that row
								if ($existingOrigin !== $origin) {
									if (!$updateStmt->bind_param("si", $origin, $existingId)) {
										$message = "Bind Param Fehler Update: (" . $updateStmt->errno . ") " . $updateStmt->error . "\n";
									} else {
										$updateStmt->execute();
										// Optional: $message = "Updated origin from '$existingOrigin' to '$origin'\n";
									}
								}
								// If origin is same => do nothing
								$position++;
								continue;
							}

							// ------------------------------------------------------
							// 8) If no row => we do an INSERT
							// ------------------------------------------------------
							if (!$insertStmt->bind_param(
								"iiiisis",
								$scheduleId,
								$groupNumber,
								$runNumber,
								$position,
								$athleteId,
								$status,
								$origin
							)) {
								$message = "Bind Param Fehler Insert: (" . $insertStmt->errno . ") " . $insertStmt->error . "\n";
								$position++;
								continue;
							}

							if (!$insertStmt->execute()) {
								$message = "Execute Fehler Insert: (" . $insertStmt->errno . ") " . $insertStmt->error . "\n";
								$position++;
								continue;
							}

							$position++;
						} // end foreach athlete
					} // end for runNumber
				} // end foreach group
			} // end foreach schedule
		} // end foreach round
	} // end foreach competition

	// Close statements
	$checkStmt->close();
	$insertStmt->close();
	$updateStmt->close();
}
?>