<?php
/*******************************************************
 * role.php - Retrieve user roles & access permissions
 * for a competition based on roles table.
 *
 * API Call: Include "Authorization: Bearer <token>" in headers.
 * GET Parameter: ?competitionCode=XXXX
 *
 * Returns:
 * {
 *   "status": true,
 *   "roles": ["Judge", "Dock Marshal"],
 *   "access": {
 *      "schedule": true,
 *      "my_schedule": false,
 *      "dock": true,
 *      "scoring": true,
 *      "judging": false,
 *      "tv": true,
 *      "team_results": false,
 *      "settings": false
 *   }
 * }
 *******************************************************/

// Function to extract Bearer token from the request headers
function getBearerToken() {
	$headers = getallheaders();
	if (!isset($headers['Authorization'])) {
		return null;
	}

	$matches = [];
	if (preg_match('/Bearer\s(\S+)/', $headers['Authorization'], $matches)) {
		return $matches[1];
	}
	return null;
}

// Extract Bearer token
$bearerToken = getBearerToken();
if (!$bearerToken) {
	echo json_encode(["status" => false, "message" => "Missing or invalid Bearer token."]);
	exit;
}

// Extract competition code
$competitionCode = isset($_GET['competitionCode']) ? trim($_GET['competitionCode']) : null;
if (!$competitionCode) {
	echo json_encode(["status" => false, "message" => "Missing competitionCode parameter."]);
	exit;
}

try {
	// 1) Fetch user record *including* council_admin + fed_admin
	$query = "
	  SELECT id, iwwf_id, council_admin, fed_admin
	  FROM user
	  WHERE bearer = ?
	  LIMIT 1
	";
	$stmt = $conn->prepare($query);
	if (!$stmt) {
		throw new Exception("Prepare failed (user): " . $conn->error);
	}
	$stmt->bind_param("s", $bearerToken);
	$stmt->execute();
	$user = $stmt->get_result()->fetch_assoc();
	$stmt->close();

	if (!$user) {
		echo json_encode(["status" => false, "message" => "User not found or invalid token."]);
		exit;
	}

	$userCode      = $user['iwwf_id'];
	$isCouncilAdmin = (int)$user['council_admin'] === 1;
	$fedAdmin       = $user['fed_admin'];  // may be NULL

	// 2) Fetch competition's organizing_country
	$query = "
	  SELECT organizing_country
	  FROM competitions
	  WHERE code = ?
	  LIMIT 1
	";
	$stmt = $conn->prepare($query);
	if (!$stmt) {
		throw new Exception("Prepare failed (competition): " . $conn->error);
	}
	$stmt->bind_param("s", $competitionCode);
	$stmt->execute();
	$compRow = $stmt->get_result()->fetch_assoc();
	$stmt->close();

	if (!$compRow) {
		echo json_encode(["status" => false, "message" => "Competition not found."]);
		exit;
	}

	$organizingCountry = $compRow['organizing_country'];

	// 3) If council_admin OR fed_admin matches, return full rights
	if ($isCouncilAdmin || ($fedAdmin !== null && $fedAdmin === $organizingCountry)) {
		$roleLabel = $isCouncilAdmin
			? "Council Admin"
			: "Federation Admin";

		echo json_encode([
			"status" => true,
			"roles"  => [$roleLabel],
			"access" => [
				"schedule"     => true,
				"my_schedule"  => true,
				"dock"         => true,
				"scoring"      => true,
				"judging"      => true,
				"tv"           => true,
				"team_results" => true,
				"settings"     => true,
				"admin"        => true
			]
		]);
		exit;
	}

	// 4) Otherwise, fetch their specific official roles & permissions
	$query = "
		SELECT 
		  o.position        AS role_name,
		  r.schedule,
		  r.my_schedule,
		  r.dock,
		  r.scoring,
		  r.judging,
		  r.tv,
		  r.team_results,
		  r.settings
		FROM officials AS o
		JOIN roles     AS r ON o.position = r.name
		WHERE o.competition_code = ?
		  AND o.iwwf_id          = ?
	";
	$stmt = $conn->prepare($query);
	if (!$stmt) {
		throw new Exception("Prepare failed (officials): " . $conn->error);
	}
	$stmt->bind_param("ss", $competitionCode, $userCode);
	$stmt->execute();
	$result = $stmt->get_result();
	$stmt->close();

	// Initialize
	$roles = [];
	$access = [
		"schedule"     => false,
		"my_schedule"  => false,
		"dock"         => false,
		"scoring"      => false,
		"judging"      => false,
		"tv"           => false,
		"team_results" => false,
		"settings"     => false,
		"admin"        => false
	];

	while ($row = $result->fetch_assoc()) {
		$roles[] = $row['role_name'];
		foreach ($access as $key => $value) {
			if (isset($row[$key]) && (int)$row[$key] === 1) {
				$access[$key] = true;
			}
		}
	}

	echo json_encode([
		"status" => true,
		"roles"  => $roles,
		"access" => $access
	]);

} catch (Exception $e) {
	echo json_encode([
		"status"  => false,
		"message" => "Error fetching user roles: " . $e->getMessage()
	]);
	exit;
}
?>