<?php

function respond($success, $dataOrError = null) {
	if ($success) {
		echo json_encode([
			'success' => true,
			'data'    => $dataOrError
		]);
	} else {
		echo json_encode([
			'success' => false,
			'error'   => $dataOrError
		]);
	}
	exit;
}

/**
 * GET: protests.php?competitionCode=XYZ[&runId=NNN]
 * Return all protests for that competition, optionally filtered by runId,
 * plus extra info such as athlete_name, run_number, etc.
 */
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
	if (!isset($_GET['competitionCode'])) {
		respond(false, "Missing competitionCode.");
	}
	$competitionCode = $_GET['competitionCode'];

	// Optional runId filter
	$runId = isset($_GET['runId']) ? intval($_GET['runId']) : null;

	// Use DISTINCT to avoid duplicate rows if the JOIN produces multiple matches:
	$sql = "
		SELECT DISTINCT
			p.id,
			p.competition_code,
			p.run_id,
			p.remark,
			p.official           AS official_id,
			p.status,
			r.run               AS run_number,
			a.first_name        AS ath_firstname,
			a.last_name         AS ath_lastname,
			o.first_name        AS off_firstname,
			o.last_name         AS off_lastname
		FROM protests p
		LEFT JOIN runs r      ON p.run_id = r.id
		LEFT JOIN athletes a  ON r.athlete = a.id
		LEFT JOIN officials o ON p.official = o.iwwf_id
		WHERE p.competition_code = ?
	";

	if ($runId) {
		$sql .= " AND p.run_id = ?";
	}
	$sql .= " ORDER BY p.id DESC";

	$stmt = $conn->prepare($sql);
	if (!$stmt) {
		respond(false, "Failed to prepare GET statement: " . $conn->error);
	}

	if ($runId) {
		$stmt->bind_param("si", $competitionCode, $runId);
	} else {
		$stmt->bind_param("s", $competitionCode);
	}

	if (!$stmt->execute()) {
		$stmt->close();
		respond(false, "Failed to execute GET: " . $conn->error);
	}

	$result = $stmt->get_result();
	$protests = [];

	while ($row = $result->fetch_assoc()) {
		// Build athlete name
		$athFirst = $row['ath_firstname'] ?? "";
		$athLast  = $row['ath_lastname']  ?? "";
		$athFullName = trim("$athFirst $athLast");
		if (!$athFullName) {
			$athFullName = "(Unknown Athlete)";
		}

		// Build official name
		$offFirst = $row['off_firstname'] ?? "";
		$offLast  = $row['off_lastname']  ?? "";
		$offFullName = trim("$offFirst $offLast");
		if (!$offFullName) {
			$offFullName = "(Unknown Official)";
		}

		$protests[] = [
			'id'               => (int) $row['id'],
			'competition_code' => $row['competition_code'],
			'run_id'           => (int) $row['run_id'],
			'remark'           => $row['remark']  ?? "",
			'official'         => $offFullName,              // Official's full name
			'official_id'      => $row['official_id'] ?? null, // iwwf_id from DB
			'status'           => (int) $row['status'],
			'run_number'       => $row['run_number'] ?? "",
			'athlete_name'     => $athFullName
		];
	}

	$stmt->close();
	respond(true, $protests);
}

/**
 * POST:
 *   1) If JSON includes { id, status }, then we're updating an existing protest's status.
 *      - If the new status = 1 (accepted), also set the run's status to 0 in runs table.
 *   2) Else if it includes { officialId, competitionCode, runId, remark }, create a new protest row with status=0.
 */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
	$input = json_decode(file_get_contents("php://input"), true);
	if (!$input) {
		respond(false, "Invalid JSON body.");
	}

	// Case 1: Update protest status
	if (isset($input['id']) && isset($input['status'])) {
		$protestId = intval($input['id']);
		$newStatus = intval($input['status']);

		// First update the protest row
		$updateSql = "UPDATE protests SET status = ? WHERE id = ?";
		$stmtUp = $conn->prepare($updateSql);
		if (!$stmtUp) {
			respond(false, "Failed to prepare update statement: " . $conn->error);
		}
		$stmtUp->bind_param("ii", $newStatus, $protestId);
		if (!$stmtUp->execute()) {
			$stmtUp->close();
			respond(false, "Failed to execute update: " . $conn->error);
		}
		$stmtUp->close();

		// If accepted => set the run's status to 0
		if ($newStatus === 1) {
			// Get the run_id from the protest
			$runIdSql = "SELECT run_id FROM protests WHERE id = ? LIMIT 1";
			$stmtRun = $conn->prepare($runIdSql);
			if (!$stmtRun) {
				respond(false, "Failed to prepare runId fetch: " . $conn->error);
			}
			$stmtRun->bind_param("i", $protestId);
			if (!$stmtRun->execute()) {
				$stmtRun->close();
				respond(false, "Failed to execute runId fetch: " . $conn->error);
			}
			$resRun = $stmtRun->get_result();
			$rowRun = $resRun->fetch_assoc();
			$stmtRun->close();

			if (!$rowRun) {
				respond(false, "Cannot find protest row to fetch run_id. Should not happen.");
			}

			$runId = intval($rowRun['run_id']);

			// Now set that run's status to 0
			$updateRunSql = "UPDATE runs SET status = 0 WHERE id = ?";
			$stmtUpdRun = $conn->prepare($updateRunSql);
			if (!$stmtUpdRun) {
				respond(false, "Failed to prepare run update: " . $conn->error);
			}
			$stmtUpdRun->bind_param("i", $runId);
			if (!$stmtUpdRun->execute()) {
				$stmtUpdRun->close();
				respond(false, "Failed to update run status: " . $conn->error);
			}
			$stmtUpdRun->close();
		}

		respond(true, "Protest status updated successfully (run status changed if accepted).");
	}

	// Case 2: Create a new protest row
	elseif (isset($input['officialId'], $input['competitionCode'], $input['runId'], $input['remark'])) {
		$officialId      = $input['officialId'];
		$competitionCode = $input['competitionCode'];
		$runId           = intval($input['runId']);
		$remark          = $input['remark'];
		
		if(isset($input['status']))
		{
			$status = $input['status'];
		}else
		{
			$status = 0;
		}

		// Insert with status=0 by default
		$insertSql = "
			INSERT INTO protests (competition_code, run_id, remark, official, status)
			VALUES (?, ?, ?, ?, ?)
		";
		$stmtIn = $conn->prepare($insertSql);
		if (!$stmtIn) {
			respond(false, "Failed to prepare insert statement: " . $conn->error);
		}
		$stmtIn->bind_param("sissi", $competitionCode, $runId, $remark, $officialId, $status);
		if (!$stmtIn->execute()) {
			$stmtIn->close();
			respond(false, "Failed to execute insert: " . $conn->error);
		}
		$newId = $stmtIn->insert_id;
		$stmtIn->close();

		respond(true, [
			"message" => "Protest created successfully.",
			"newId"   => $newId
		]);
	}

	else {
		respond(false, "Missing or invalid fields for protest creation or update.");
	}
}

// If we get here, method not supported
respond(false, "Unsupported request method.");
?>