<?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');
	
	$winNumber = $_POST['winNumber'];
	$limitPerQuestion = $_POST['limitPerQuestion'];
	$limitPerPlayer = $_POST['limitPerPlayer'];
	$playerIds = $_POST['playerIds'];
	$currentUser = $_POST['currentUser'];
	
	$playerIdsArray = explode(",",$playerIds);
	$playerCount = count($playerIdsArray);
	if ($playerCount == 1) {
		$status = "STARTED";
	} else {
		$status = "PENDING";
	}
	$sql = "INSERT INTO game(" .
            "gameMode, " .
			"status, " .
            "winNumber, " .
            "answerTimer, " .
            "roundTimeLimit, " .
            "numberOfPlayers, " .
            "currentPlayer, " .
            "round, " .
            "startedDate) " .
            "VALUES (" .
            "'Online', " .
			"'$status', " .
            "$winNumber, " .
            "$limitPerQuestion, " .
            "$limitPerPlayer, " .
            "$playerCount, " .
            "(SELECT id FROM users WHERE id IN ($playerIds) ORDER BY RAND() LIMIT 1), " .
            "1, " .
            "NOW())";
	
	$result = mysqli_query($conn, $sql);
	$error = mysqli_error($conn);
	if ($error !== "") {
		echo $error;
	}
	$gameId = mysqli_insert_id($conn);
	$playerPartInsertSql = "";
	foreach ($playerIdsArray AS $playerId) {
		if ($currentUser == $playerId) {
			$playerPartInsertSql .= "($gameId, $playerId, 1, 1, 'ACCEPTED'),";
		} else {
			$playerPartInsertSql .= "($gameId, $playerId, 1, 1, 'WAITING'),";
		}
	}
	$playerPartInsertSql = rtrim($playerPartInsertSql,",");
	$playerSql = "INSERT INTO gamePlayers (gameId, playerId, userLockedQuestions, questionsLost, status) VALUES $playerPartInsertSql";
	
	$result = mysqli_query($conn,$playerSql);
	$error = mysqli_error($conn);
	if ($error !== "") {
		echo $error . " from sql " . $playerSql;
	}

?>
