<?php

// SQL query to fetch the required data from competitions and athletes tables
$sql = "
	SELECT 
		c.id, 
		c.code,
		c.name AS event_name, 
		c.beginning_date, 
		c.end_date, 
		c.venue, 
		c.tournament_type AS type, 
		c.discipline AS disciplines, 
		c.age_group AS categories, 
		(SELECT COUNT(*) FROM athletes WHERE athletes.competition_code = c.code) AS athletes_registered,
		c.timestamp AS last_import, 
		'Judge' AS my_role,  -- This is hardcoded as placeholder; change it if needed
		'assets/img/QR_code_for_mobile_English_Wikipedia.svg.png' AS qr_code_link, -- Hardcoded QR code placeholder
		1 AS selected,  -- Example value, replace as needed
		0 AS export_results -- Example value, replace as needed
	FROM competitions c";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
	$response = array();

	// Fetch the event data
	while ($row = $result->fetch_assoc()) {
		// Build the JSON response structure
		$response[] = array(
			"event" => array(
				"id" => $row["id"],
				"code" => $row["code"],
				"name" => $row["event_name"],
				"dates" => $row["beginning_date"] . " - " . $row["end_date"],
				"location" => $row["venue"],
				"type" => $row["type"],
				"disciplines" => explode(", ", $row["disciplines"]),  // Convert string to array
				"categories" => explode(", ", $row["categories"]),    // Convert string to array
				"athletes_registered" => (int) $row["athletes_registered"],
				"last_import" => $row["last_import"],
				"my_role" => $row["my_role"],
				"qr_code_link" => $row["qr_code_link"],
				"selected" => (int) $row["selected"],
				"export_results" => (int) $row["export_results"]
			)
		);
	}

	// Return the JSON response
	echo json_encode($response, JSON_PRETTY_PRINT);
} else {
	echo json_encode(array("message" => "No events found."));
}

?>