<?php
    require __DIR__ . "/../vendor/autoload.php";

    use Kreait\Firebase\Factory;
	use Kreait\Firebase\Messaging\Notification;
	use Kreait\Firebase\Messaging\CloudMessage;
	use Kreait\Firebase\Messaging\FcmOptions;

// Connection to db
	$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');
	
	// Constants
	$messageType = $conn->real_escape_string(isset($_POST['type'])?$_POST['type']:"");
	$title = $conn->real_escape_string($_POST['title']);
	$messageToSend = $_POST['message'];
	$gameId = $conn->real_escape_string($_POST['GameId']);

	if ($messageType === "FCMNextPlayer") {
		$playerName = $conn->real_escape_string($_POST['playerName']);
		$deviceToken = getToken($conn, $gameId, $playerName);
		
		if ($deviceToken != null && $deviceToken != "") {
			sendMessage($title, $messageToSend, $deviceToken, "NextPlayer");
		}
	} else if ($messageType === "gameFinishedMessage") {
		$i = 0;
		while ($_POST['player' . $i] != null) {
			$deviceToken = getToken($conn, $gameId, $conn->real_escape_string($_POST['player' . $i]));
			if ($deviceToken != null && $deviceToken != "") {
				sendMessage($title, $messageToSend, $deviceToken, "GameFinished");
			}
			$i++;
		}
	} else if ($messageType === "InviteMessage") {
		$i = 0;
		while ($_POST['player' . $i] != null) {
			$deviceToken = getToken($conn, $gameId, $conn->real_escape_string($_POST['player' . $i]));
			if ($deviceToken != null && $deviceToken != "") {
				sendMessage($title, $messageToSend, $deviceToken, "GameInvite");
			}
			$i++;
		}
	}
	
    function sendMessage($title, $messageToSend, $deviceToken, $tag = "") {
        $factory = (new Factory)->withServiceAccount("../narkampen-firebase-adminsdk-k42j5-d3d0354e37.json");
        $messaging = $factory->createMessaging();
        $notification = Notification::create($title, $messageToSend);

        if ($tag !== "") {
            $fcmOptions = FcmOptions::create()->withAnalyticsLabel($tag);
        }

        if ($fcmOptions != null) {
                $message = CloudMessage::withTarget(
            'token', $deviceToken)
            ->withNotification($notification)
            ->withFcmOptions($fcmOptions);

        } else {
            $message = CloudMessage::withTarget(
                'token', $deviceToken)
                ->withNotification($notification);
        }

		file_put_contents("FirebaseCallerDebug.php", "Sending message with title $title", FILE_APPEND);
        $messaging->send($message);
    }

	
	/*
	// NOTIFICATION EXAMPLE
	$title = 'My Notification Title';
	$body = 'My Notification Body';
	$imageUrl = 'http://lorempixel.com/400/200/';

	$notification = Notification::fromArray([
		'title' => $title,
		'body' => $body,
		'image' => $imageUrl,
	]);

	$notification = Notification::create($title, $body);

	$changedNotification = $notification
		->withTitle('Changed title')
		->withBody('Changed body')
		->withImageUrl('http://lorempixel.com/200/400/');

	$message->withNotification($notification);
	// NOTIFICATION EXAMPLE END	
	
	// DATA Example
	$data = [
		'first key' => "First value",
		"second key" => "Second value"];
		
	$message->withData($data);
	// DATA EXAMPLE END
	
	$message = CloudMessage::withTarget('token', $deviceToken)
		->withNotification($notification) // OPTIONAL
		->withData($data); // OPTIONAL
		
		
	$message = CloudMessage::fromArray([
		'token' => $deviceToken,
		'notification' => [],
		'data' => []
		]);
		
		
	$messaging->send($message);
	
	*/
	
	function getToken($conn, $gameId, $playerName) {
		$sql = "SELECT messageToken FROM `gamePlayers` INNER JOIN users ON users.id = playerId WHERE gameId = $gameId and users.username = '$playerName'";

		$result = $conn->query($sql);
		if ($result->num_rows == 1) {
			$returnArray = array();
			$data = $result->fetch_assoc();
			$token = $data['messageToken'];
		} else {
			echo "No games found for user";
		}
		return $token;
	}