<?php

$competitionCode = $_GET['competitionCode'] ?? null;

if (!$competitionCode) {
	echo json_encode(['success' => false, 'error' => 'Competition code is required.']);
	exit;
}

try {
	// Query to fetch officials related to the competition along with their id and password status
	$query = "
		SELECT 
			o.id AS official_id, 
			o.iwwf_id, 
			o.first_name, 
			o.last_name, 
			o.position, 
			o.country, 
			u.email, 
			CASE 
				WHEN u.password IS NOT NULL AND u.password != '' THEN 1 
				ELSE 0 
			END AS password_set
		FROM officials o
		LEFT JOIN user u ON o.iwwf_id = u.iwwf_id
		WHERE o.competition_code = ?
	";
	$stmt = $conn->prepare($query);
	$stmt->bind_param("s", $competitionCode);
	$stmt->execute();
	$result = $stmt->get_result();

	$officials = [];
	while ($row = $result->fetch_assoc()) {
		$officials[] = $row;
	}

	if (empty($officials)) {
		echo json_encode(['success' => false, 'error' => 'No officials found for the specified competition.']);
		exit;
	}

	echo json_encode(['success' => true, 'officials' => $officials]);
} catch (Exception $e) {
	http_response_code(500); // Internal Server Error
	echo json_encode(['success' => false, 'error' => 'Unexpected error: ' . $e->getMessage()]);
	exit;
}
?>