<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
	// decode the incoming JSON
	$input = json_decode(file_get_contents("php://input"), true);

	if (!isset($input['schedule_id'], $input['new_order'])) {
		echo json_encode(["success" => false, "message" => "Missing parameters (schedule_id, new_order)."]);
		exit;
	}

	$scheduleId = intval($input['schedule_id']);
	$newOrder   = intval($input['new_order']);

	// 1) Find the old order + competition for this schedule
	$sql = "SELECT `order`, comp 
			FROM schedule 
			WHERE id = ?
			LIMIT 1";
	$stmt = $conn->prepare($sql);
	$stmt->bind_param("i", $scheduleId);
	$stmt->execute();
	$result = $stmt->get_result();
	$currentRow = $result->fetch_assoc();
	$stmt->close();

	if (!$currentRow) {
		echo json_encode(["success" => false, "message" => "No schedule row found with that ID."]);
		exit;
	}

	$oldOrder        = (int)$currentRow['order'];
	$competitionCode = $currentRow['comp'];

	// 2) Check if there's already some schedule in this competition that has the same $newOrder
	//    We'll call this the "colliding" row if it exists
	$sqlCheck = "SELECT id 
				 FROM schedule 
				 WHERE `comp` = ?
				   AND `order` = ?
				   AND id <> ?  -- exclude the row we are moving
				 LIMIT 1";
	$stmtCheck = $conn->prepare($sqlCheck);
	$stmtCheck->bind_param("sii", $competitionCode, $newOrder, $scheduleId);
	$stmtCheck->execute();
	$resCheck = $stmtCheck->get_result();
	$collidingRow = $resCheck->fetch_assoc();
	$stmtCheck->close();

	// Start a transaction so we can do the swap (or single update) atomically
	$conn->begin_transaction();

	try {
		// 3) If there's a colliding schedule => swap
		if ($collidingRow) {
			$otherScheduleId = (int)$collidingRow['id'];

			// Step A: Update the colliding row to take our old order
			$sqlUpdateOther = "UPDATE schedule
							   SET `order` = ?
							   WHERE id = ?";
			$stmtOther = $conn->prepare($sqlUpdateOther);
			$stmtOther->bind_param("ii", $oldOrder, $otherScheduleId);
			$stmtOther->execute();
			$stmtOther->close();

			// Step B: Update our row to take the new order
			$sqlUpdateMe = "UPDATE schedule
							SET `order` = ?
							WHERE id = ?";
			$stmtMe = $conn->prepare($sqlUpdateMe);
			$stmtMe->bind_param("ii", $newOrder, $scheduleId);
			$stmtMe->execute();
			$stmtMe->close();

			// Commit
			$conn->commit();
			echo json_encode([
				"success" => true,
				"message" => "Swapped orders successfully with row #{$otherScheduleId}."
			]);
		} 
		else {
			// 4) No collision => just update our row
			$sqlUpdate = "UPDATE schedule
						  SET `order` = ?
						  WHERE id = ?";
			$stmtUpdate = $conn->prepare($sqlUpdate);
			$stmtUpdate->bind_param("ii", $newOrder, $scheduleId);
			$stmtUpdate->execute();
			$stmtUpdate->close();

			$conn->commit();
			echo json_encode([
				"success" => true,
				"message" => "Updated order without collision."
			]);
		}
	} 
	catch (Exception $ex) {
		$conn->rollback();
		echo json_encode([
			"success" => false,
			"message" => "Transaction failed: " . $ex->getMessage()
		]);
	}
} 
else {
	echo json_encode(["success" => false, "message" => "Invalid request method."]);
}
?>