<?php
	error_reporting( E_ALL );
	$hostname = 'localhost';
	$username = 'narKampen';
	$pass = 'IfRLzj2HJBXA9eei';
	$database = 'narKampen';

	$conn = new mysqli($hostname, $username, $pass, $database);
	
	if (!$conn) {
		die("Connection Failed. ". mysqli_connect_error());
	}
	mysqli_set_charset($conn,'utf8');
	
	$function = $_POST["f"];

	if ($function === "PlayerSearch") {
		$searchString = $_POST["SearchString"];
		
		$sql = "SELECT id, username FROM users WHERE username LIKE '%$searchString%' LIMIT 20";
		
		$result = mysqli_query($conn, $sql);
		
		$json = array();
		
		if (mysqli_num_rows($result) > 0) {
			while ($row = mysqli_fetch_assoc($result)) {
				$json[] = array('id' => $row['id'],
				'username' => $row['username']);
			}
			$jsonString = json_encode($json);
			echo $jsonString;
		} else {
			echo "";
		}
	} else if ($function === "FindRandomPlayers") {
		$currentPlayerId = $_POST['playerId'];
		$sql = "SELECT id, username FROM users WHERE id != $currentPlayerId ORDER BY RAND() LIMIT 10";

		$result = mysqli_query($conn, $sql);
		if (mysqli_num_rows($result) > 0) {
			$json = array();
			while ($row = mysqli_fetch_assoc($result)) {
				$json[] = array('id' => $row["id"],
				'username' => $row["username"]);
			}

			echo json_encode($json);
		} else {
			echo "";
		}
	} else {
		echo "No Function Found";
	}
		
?>
