<?php
header('Content-Type: application/json');

try {
	// Check request method:
	if ($_SERVER['REQUEST_METHOD'] === 'POST') {
		// 1) Handle POST => update fed_admin
		$inputJson = file_get_contents('php://input');
		$inputData = json_decode($inputJson, true);

		if (!$inputData || !isset($inputData['user_id']) || !isset($inputData['fed_admin'])) {
			echo json_encode([
				'success' => false,
				'error'   => 'Invalid JSON or missing parameters (user_id, fed_admin).'
			]);
			exit;
		}

		$userId   = intval($inputData['user_id']);
		$fedAdmin = trim($inputData['fed_admin']); // e.g., "GER", or ""

		// Prepare and execute update
		$updateSql = "UPDATE user SET fed_admin = ? WHERE id = ? LIMIT 1";
		$stmt = $conn->prepare($updateSql);
		if (!$stmt) {
			echo json_encode([
				'success' => false,
				'error'   => 'Failed to prepare statement: ' . $conn->error
			]);
			exit;
		}
		$stmt->bind_param("si", $fedAdmin, $userId);
		$stmt->execute();

		if ($stmt->affected_rows >= 0) {
			// Success (affected_rows could be 0 if no actual change)
			echo json_encode([
				'success' => true,
				'message' => "fed_admin updated for user #$userId => '$fedAdmin'"
			]);
		} else {
			// Some DB error
			echo json_encode([
				'success' => false,
				'error'   => 'DB error: ' . $stmt->error
			]);
		}
		$stmt->close();
		exit;
	} 
	else {
		// 2) Handle GET => your existing logic to fetch users + countries
		//    (Same as the code you posted, just inside this else block)

		// 1) Query all users + officials
		$sql = "
			SELECT
				u.id            AS user_id,
				u.iwwf_id       AS user_iwwf,
				u.email         AS user_email,
				u.password      AS user_password,   -- for official_status
				u.fed_admin,
				u.council_admin,
				u.timestamp,
				
				o.id            AS official_id,
				o.first_name    AS official_first_name,
				o.last_name     AS official_last_name,
				o.position      AS official_position,
				o.country       AS official_country,
				o.competition_code,
				
				c.name          AS country_name,
				
				co.code         AS competition_code_join,     -- avoid overshadowing o.competition_code
				co.name         AS competition_name,
				co.venue        AS competition_venue,
				co.beginning_date AS beginning_date,
				co.end_date     AS end_date,
				co.organizing_country AS competition_country

			FROM user u
			LEFT JOIN officials o
				ON u.iwwf_id = o.iwwf_id
			LEFT JOIN countries c
				ON u.fed_admin = c.code
			LEFT JOIN competitions co
				ON o.competition_code = co.code
			ORDER BY o.last_name ASC
		";
		
		$stmt = $conn->prepare($sql);
		$stmt->execute();
		$result = $stmt->get_result();

		$usersMap = []; // We'll map user_id => user data + 'officials' array

		while ($row = $result->fetch_assoc()) {
			$userId = $row['user_id'];
			
			// If we've not seen this userId yet, initialize
			if (!isset($usersMap[$userId])) {
				// Decide official_status => 1 if password not null/empty, else 0
				$isPasswordSet = (!empty($row['user_password'])) ? 1 : 0;

				$usersMap[$userId] = [
					'user_id'        => $row['user_id'],
					'iwwf_id'        => $row['user_iwwf'],
					'email'          => $row['user_email'],
					'fed_admin'      => $row['fed_admin'],
					'council_admin'  => $row['council_admin'],
					'timestamp'      => $row['timestamp'],
					'country'        => $row['country_name'] ?: null, // from left join
					'first_name'     => $row['official_first_name'] ?: '', 
					'last_name'      => $row['official_last_name']  ?: '',
					'official_status'=> $isPasswordSet,
					'officials'      => []
				];
			}

			// If we have an official_id => there's a valid match in officials
			if (!empty($row['official_id'])) {
				$usersMap[$userId]['officials'][] = [
					'official_id'         => $row['official_id'],
					'official_position'   => $row['official_position'],
					'official_country'    => $row['official_country'],
					'competition_code'    => $row['competition_code'],
					'competition_name'    => $row['competition_name'],
					'competition_country' => $row['competition_country'],
					'competition_venue'   => $row['competition_venue'],
					'beginning_date'      => $row['beginning_date'],
					'end_date'            => $row['end_date'],
				];
			}
		}

		$usersList = array_values($usersMap);

		// 2) Second query: get all countries => (id, code, name)
		$countriesQuery = "SELECT id, code, name FROM countries ORDER BY name ASC";
		$countriesResult = $conn->query($countriesQuery);

		$allCountries = [];
		if ($countriesResult && $countriesResult->num_rows > 0) {
			while ($cRow = $countriesResult->fetch_assoc()) {
				$allCountries[] = [
					'id'   => $cRow['id'],
					'code' => $cRow['code'],
					'name' => $cRow['name']
				];
			}
		}

		// 3) Return JSON with both "users" and "countries"
		echo json_encode([
			'status'    => 'success',
			'count'     => count($usersList),
			'users'     => $usersList,
			'countries' => $allCountries
		]);
	}

} catch (Exception $e) {
	http_response_code(500);
	echo json_encode([
		'status' => 'error',
		'error'  => $e->getMessage()
	]);
	exit;
}

?>