<?php

// Include function and connection files
include 'dbconnect.php';
include 'functions/categories.php';
include 'functions/rounds_to_schedule.php';
include 'functions/runs.php';
include 'functions/snake.php';
include 'functions/step-ladder.php';
include 'functions/ladder.php';
include 'functions/startlists.php';
include 'functions/athletes.php';

/**
 * Ensure a settings entry exists, applying special heatsystem logic.
 */
function ensureSettingsEntry($conn, $competitionCode, $discipline, $organizingCountry, $tournamentCode) {
	// Determine heatsystem based on discipline, country, and tournament code
	if (
		$discipline === "Cable Wakeboard"
		&& $organizingCountry === "GER"
		&& in_array($tournamentCode, ["CT736", "CT735", "CT731"], true)
	) {
		$heatsystem = 3;
	} elseif ($discipline === "Cable Wakeboard" && in_array($tournamentCode, ["CT716"], true)) {
		$heatsystem = 4;
	} elseif ($discipline === "Cable Wakeboard") {
		$heatsystem = 1;
	} else {
		$heatsystem = 2;
	}

	// Fixed values
	$runtime = 180;
	$judges  = 3;
	$mode    = 1;
	$judging = 1;

	// Check if entry already exists
	$query = "SELECT id FROM settings WHERE competition_code = ? LIMIT 1";
	$stmt  = $conn->prepare($query);
	if (!$stmt) {
		return "Error preparing settings lookup: " . $conn->error;
	}

	$stmt->bind_param("s", $competitionCode);
	if (!$stmt->execute()) {
		$stmt->close();
		return "Error executing settings lookup: " . $conn->error;
	}
	$stmt->store_result();

	if ($stmt->num_rows === 0) {
		$insertQuery = "
			INSERT INTO settings
				(competition_code, heatsystem, runtime, judges, mode, judging)
			VALUES
				(?, ?, ?, ?, ?, ?)
		";
		$insertStmt = $conn->prepare($insertQuery);
		if (!$insertStmt) {
			$stmt->close();
			return "Error preparing settings insert: " . $conn->error;
		}

		$insertStmt->bind_param(
			"siiiii",
			$competitionCode,
			$heatsystem,
			$runtime,
			$judges,
			$mode,
			$judging
		);
		if (!$insertStmt->execute()) {
			$result = "Error inserting settings: " . $conn->error;
		} else {
			$result = "Settings entry created successfully.";
		}
		$insertStmt->close();
	} else {
		$result = "Settings entry already exists for competition: {$competitionCode}.";
	}

	$stmt->close();
	return $result;
}

/**
 * Get all event IDs for a competition.
 */
function getEventIdsForCompetition($conn, $competitionCode) {
	$query = "SELECT id FROM events WHERE competition_code = ?";

	$stmt = $conn->prepare($query);
	if (!$stmt) {
		return [];
	}
	$stmt->bind_param("s", $competitionCode);
	if (!$stmt->execute()) {
		$stmt->close();
		return [];
	}

	$result = $stmt->get_result();
	$eventIds = [];
	while ($row = $result->fetch_assoc()) {
		$eventIds[] = $row['id'];
	}
	$stmt->close();
	return $eventIds;
}

/**
 * Fetch the organizing country code for a competition.
 */
function getOrganizerForCompetition(mysqli $conn, string $competitionCode): ?string {
	$query = "SELECT organizing_country FROM competitions WHERE code = ? LIMIT 1";
	if (! $stmt = $conn->prepare($query)) {
		return null;
	}
	$stmt->bind_param("s", $competitionCode);
	if (! $stmt->execute()) {
		$stmt->close();
		return null;
	}
	$res = $stmt->get_result();
	$organizer = $res->fetch_assoc()['organizing_country'] ?? null;
	$stmt->close();
	return $organizer;
}

/**
 * Fetch the tournament code for a competition.
 */
function getTournamentForCompetition(mysqli $conn, string $competitionCode): ?string {
	$query = "SELECT tournament_code FROM competitions WHERE code = ? LIMIT 1";
	if (! $stmt = $conn->prepare($query)) {
		return null;
	}
	$stmt->bind_param("s", $competitionCode);
	if (! $stmt->execute()) {
		$stmt->close();
		return null;
	}
	$res = $stmt->get_result();
	$tournament = $res->fetch_assoc()['tournament_code'] ?? null;
	$stmt->close();
	return $tournament;
}

/**
 * Fetch the discipline for a competition.
 */
function getDisciplineByCompetitionCode($conn, $competitionCode) {
	$query = "SELECT discipline FROM competitions WHERE code = ? LIMIT 1";
	$stmt = $conn->prepare($query);
	if (!$stmt) {
		return null;
	}
	$stmt->bind_param("s", $competitionCode);
	if (!$stmt->execute()) {
		$stmt->close();
		return null;
	}
	$res = $stmt->get_result();
	$discipline = $res->fetch_assoc()['discipline'] ?? null;
	$stmt->close();
	return $discipline;
}

// ------------ MAIN SCRIPT ------------

// Ensure competitionCode is defined (e.g., from GET or CLI)
if (!isset($competitionCode)) {
	die('Error: competitionCode not specified.');
}

// 1) Ensure settings entry exists
$discipline        = getDisciplineByCompetitionCode($conn, $competitionCode);
$organizingCountry = getOrganizerForCompetition($conn, $competitionCode);
$tournamentCode    = getTournamentForCompetition($conn, $competitionCode);

if ($discipline === null || $organizingCountry === null || $tournamentCode === null) {
	die('Error: could not load competition metadata.');
}

$settingsResult = ensureSettingsEntry(
	$conn,
	$competitionCode,
	$discipline,
	$organizingCountry,
	$tournamentCode
);
if (strpos($settingsResult, 'Error') === 0) {
	die("Settings setup failed: {$settingsResult}");
}

// 2) Build rounds & schedule
$eventIds = getEventIdsForCompetition($conn, $competitionCode);

foreach ($eventIds as $event_id) {
	$athleteCounts = getAthleteCountPerCategory($conn, $competitionCode, $event_id);
	foreach ($athleteCounts as $categoryId => $counts) {
		foreach ($counts as $gender => $athleteCount) {
			ob_start();
			addHeatsystemRoundsToSchedule(
				$conn,
				$competitionCode,
				$event_id,
				$categoryId,
				$gender,
				$athleteCount
			);
			ob_end_clean();
		}
	}
}

// 3) Generate runs & start lists
$jsonData       = generateCompetitionRuns($conn, $competitionCode);
generateRunsFromJson($conn, $jsonData);

$athletes_start = groupAthletesByEventCategoryGender($conn, $competitionCode);
updateRunsWithAthleteIdFromJson($conn, $athletes_start);

?>