<?php

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
	$competitionCode = $_GET['competitionCode'] ?? null;

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

	try {
		// Fetch competition ID
		$competitionQuery = "SELECT id FROM competitions WHERE code = ?";
		$stmt = $conn->prepare($competitionQuery);
		$stmt->bind_param("s", $competitionCode);
		$stmt->execute();
		$competitionResult = $stmt->get_result();
		$competition = $competitionResult->fetch_assoc();
		$stmt->close();

		if (!$competition) {
			echo json_encode(['success' => false, 'error' => 'Invalid competition code.']);
			exit;
		}

		$competitionId = $competition['id'];

		// Fetch number of judges from settings
		$settingsQuery = "SELECT judges FROM settings WHERE competition_code = ?";
		$stmt = $conn->prepare($settingsQuery);
		$stmt->bind_param("s", $competitionCode);
		$stmt->execute();
		$settingsResult = $stmt->get_result();
		$numberOfJudges = $settingsResult->fetch_assoc()['judges'] ?? 3;
		$stmt->close();

		// Fetch events for this competition
		$eventsQuery = "SELECT id, event_code, event_name AS name FROM events WHERE competition_code = ?";
		$stmt = $conn->prepare($eventsQuery);
		$stmt->bind_param("s", $competitionCode);
		$stmt->execute();
		$eventsResult = $stmt->get_result();
		$events = $eventsResult->fetch_all(MYSQLI_ASSOC);
		$stmt->close();

		// Fetch all officials for this competition
		$officialsQuery = "
			SELECT 
				o.id AS official_id,
				CONCAT(o.first_name, ' ', o.last_name) AS name,
				o.position,
				o.country,
				o.iwwf_id
			FROM officials o
			WHERE o.competition_code = ?
		";
		$stmt = $conn->prepare($officialsQuery);
		$stmt->bind_param("s", $competitionCode);
		$stmt->execute();
		$officialsResult = $stmt->get_result();
		$officials = $officialsResult->fetch_all(MYSQLI_ASSOC);
		$stmt->close();

		// Process events and categories
		foreach ($events as &$event) {
			$categoriesQuery = "
				SELECT DISTINCT 
					c.id AS category_id,
					c.code AS category_code,
					c.name AS category_name,
					c.gender AS category_gender,
					(
					  SELECT COUNT(*)
					  FROM athletes a 
					  WHERE a.category_in_competition = c.code
						AND a.event_code = ?
						AND c.gender = a.gender
					) AS category_athletes,
					(
					  SELECT COUNT(*)
					  FROM runs r
					  JOIN schedule s ON r.schedule = s.id
					  JOIN events e2 ON s.event = e2.id
					  WHERE e2.event_code = ?
						AND s.category = c.id
					) AS category_runs
				FROM categories c
				WHERE EXISTS (
					SELECT 1
					FROM schedule s
					JOIN events e ON s.event = e.id
					WHERE s.category = c.id
					AND e.id = ?
					AND e.competition_code = ?
				)
			";
			$stmt = $conn->prepare($categoriesQuery);
			$stmt->bind_param("ssis", $event['event_code'], $event['event_code'], $event['id'], $competitionCode);
			$stmt->execute();
			$categoriesResult = $stmt->get_result();
			$categories = $categoriesResult->fetch_all(MYSQLI_ASSOC);
			$stmt->close();

			// Filter categories with athletes
			$categories = array_values(array_filter($categories, function ($category) {
				return $category['category_athletes'] > 0;
			}));

			// Add officials for each valid category
			foreach ($categories as &$category) {
				$officialsPanelQuery = "
					SELECT 
						op.id AS panel_id,
						op.official AS official_id,
						op.judge AS judge,
						CONCAT(o.first_name, ' ', o.last_name) AS name,
						o.position,
						o.country,
						o.iwwf_id
					FROM officials_panel op
					JOIN officials o ON op.official = o.id
					WHERE op.competition = ? AND op.event = ? AND op.category = ?
				";
				$stmt = $conn->prepare($officialsPanelQuery);
				$stmt->bind_param("iii", $competitionId, $event['id'], $category['category_id']);
				$stmt->execute();
				$officialsPanelResult = $stmt->get_result();
				$officialsForCategory = $officialsPanelResult->fetch_all(MYSQLI_ASSOC);
				$stmt->close();

				$category['officials'] = $officialsForCategory;
			}

			$event['categories_in_competition'] = $categories;
		}

		echo json_encode([
			'success' => true,
			'number_of_judges' => (int)$numberOfJudges,
			'events' => $events,
			'officials' => $officials
		]);
	} catch (Exception $e) {
		http_response_code(500);
		echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
		exit;
	}
}elseif ($method === 'POST') {
	$input = json_decode(file_get_contents('php://input'), true);

	$competitionCode = $input['competitionCode'] ?? null;
	$judges = $input['judges'] ?? null;

	if (!$competitionCode || !$judges || !is_array($judges)) {
		echo json_encode(['success' => false, 'error' => 'Invalid data provided.']);
		exit;
	}

	try {
		// Get competition ID
		$competitionQuery = "SELECT id FROM competitions WHERE code = ?";
		$stmt = $conn->prepare($competitionQuery);
		$stmt->bind_param("s", $competitionCode);
		$stmt->execute();
		$competitionResult = $stmt->get_result();
		$competition = $competitionResult->fetch_assoc();
		$stmt->close();

		if (!$competition) {
			echo json_encode(['success' => false, 'error' => 'Invalid competition code.']);
			exit;
		}

		$competitionId = $competition['id'];

		// Insert or update judge assignments
		foreach ($judges as $judge) {
			$categoryId = $judge['category_id'];
			$eventId = $judge['event_id'];
			$judgeIndex = $judge['judge_index'];
			$officialId = $judge['official_id'];

			// Check if the entry exists
			$checkQuery = "
				SELECT id 
				FROM officials_panel 
				WHERE competition = ? AND event = ? AND category = ? AND judge = ?
			";
			$stmt = $conn->prepare($checkQuery);
			$stmt->bind_param("iiii", $competitionId, $eventId, $categoryId, $judgeIndex);
			$stmt->execute();
			$result = $stmt->get_result();
			$existingRow = $result->fetch_assoc();
			$stmt->close();

			if ($existingRow) {
				// Update the existing row
				$updateQuery = "
					UPDATE officials_panel
					SET official = ?
					WHERE id = ?
				";
				$stmt = $conn->prepare($updateQuery);
				$stmt->bind_param("ii", $officialId, $existingRow['id']);
				$stmt->execute();
				$stmt->close();
			} else {
				// Insert a new row
				$insertQuery = "
					INSERT INTO officials_panel (competition, event, category, official, judge)
					VALUES (?, ?, ?, ?, ?)
				";
				$stmt = $conn->prepare($insertQuery);
				$stmt->bind_param("iiiii", $competitionId, $eventId, $categoryId, $officialId, $judgeIndex);
				$stmt->execute();
				$stmt->close();
			}
		}

		echo json_encode(['success' => true, 'message' => 'Judges saved successfully.']);
	} catch (Exception $e) {
		http_response_code(500);
		echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
	}
} else {
	http_response_code(405);
	echo json_encode(['success' => false, 'error' => 'Method not allowed.']);
}
?>