<?php
require_once 'core/classes.php';
require_once 'core/classes/user.php';
header('content-type:plain/text');
ob_start();
session_start();
$user = new User($con, $_SESSION['user'] ?? 0);
if(!$user->isLoggedIn()) {
  header('location: /login');
  exit;
}
$placeid = $_GET['placeid'];
if (!isset($placeid)) {
	echo "No placeid";
	exit;
}
$username = $user->getUsername();
$id = $user->getID($con, $user->getUsername());
function generateRandomString($length = 25) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[random_int(0, $charactersLength - 1)];
    }
    return $randomString;
} // pls don't hurt me
$checkifuser = $con->prepare('SELECT COUNT(*) FROM games WHERE id=:placeid');
$checkifuser->bindParam(':placeid', $placeid);
$checkifuser->execute();
$momentoftruth = $checkifuser->fetchColumn();
if ($momentoftruth == 1) {
	$token = generateRandomString(500);
    $fbi = $con->prepare('INSERT INTO tokens (token, placeid, userid) VALUES (:token, :placeid, :userid)');
    $fbi->bindParam(':token', $token);
    $fbi->bindParam(':placeid', $placeid);
    $fbi->bindParam(':userid', $id);
    $fbi->execute();
    die($token);
} else {
	echo 'No placeId found';
    exit;
}
?>
