<?php
require_once '../core/config.php';
require_once '../core/Roblox/Grid/Rcc/Job.php';
require_once '../core/Roblox/Grid/Rcc/LuaType.php';
require_once '../core/Roblox/Grid/Rcc/LuaValue.php';
require_once '../core/Roblox/Grid/Rcc/RCCServiceSoap.php';
require_once '../core/Roblox/Grid/Rcc/ScriptExecution.php';
require_once '../core/Roblox/Grid/Rcc/Status.php';
header('content-type:application/json');
$allstatus = [
    1 => "0 or 1 is not an error - it is a sign that we should wait",
    2 => "Success",
    3 => "Disabled",
    4 => "Failed to start",
    5 => "Game ended",
    6 => "GAME_FULL",
	10 => "USER_LEFT"
];
$token = $_GET["token"];
$checkifuser = $con->prepare('SELECT COUNT(*) FROM tokens WHERE token=:token');
$checkifuser->bindParam(':token', $token);
$checkifuser->execute();
$momentoftruth = $checkifuser->fetchColumn();
if ($momentoftruth == 1) {
	$status = '2';
	$getstuff = $con->prepare('SELECT placeid FROM tokens WHERE token=:token');
	$getstuff->bindParam(':token', $token);
    $getstuff->execute();
	$china = $getstuff->fetch(PDO::FETCH_BOTH);
    $placeid = $china['placeid'];
    $haha = $con->prepare('SELECT COUNT(*) FROM tokens WHERE token=:token AND passedplacelauncher=:passed');
    $haha->bindParam(':token', $token);
	$haha->bindParam(':passed', $okbruh);
    $haha->execute();
	$moretrolling = $haha->fetchColumn();
    if ($moretrolling == 1) {
	header("Location: /");
	} else if ($moretrolling == 0) {
	$checkifjobalreadyexists = $con->prepare('SELECT COUNT(*) FROM jobs WHERE placeid=:placeid AND isonline=:isonline');
    $checkifjobalreadyexists->bindParam(':placeid', $placeid);
	$helppdo = '1';
	$checkifjobalreadyexists->bindParam(':isonline', $helppdo);
    $checkifjobalreadyexists->execute();
	$okcheck = $checkifjobalreadyexists->fetchColumn();
	if ($okcheck == 1) {
	$getjobforalready = $con->prepare('SELECT jobid FROM jobs WHERE placeid=:placeid AND isonline=:isonline');
	$getjobforalready->bindParam(':placeid', $placeid);
        $getjobforalready->bindParam(':isonline', $helppdo);
    $getjobforalready->execute();
	$china2 = $getjobforalready->fetch(PDO::FETCH_BOTH);
    $jobid = $china2['jobid'];
    $response = [
        "jobId" => $jobid,
        "status" => $status,
        "joinScriptUrl" => "http://". $soapcfg['url'] ."/game/join?token=". $token ."&jobid=". $jobid,
        "authenticationUrl" => "http://". $soapcfg['url'] ."/Login/Negotiate.ashx",
        "authenticationTicket" => $token,
        "message" => $allstatus[$status]
    ];
	echo json_encode($response);
	} else if ($okcheck == 0) {
		$hahatroll = $con->prepare('UPDATE tokens SET passedplacelauncher = 1 WHERE token=:token');
	    $hahatroll->bindParam(':token', $token);
        $hahatroll->execute();
	   function generateRandomJobId() {
       $chars = '0123456789abcdefghijklmnopqrstuvwxyz';
       $length = 8;
       $p1 = substr(str_shuffle(str_repeat($x=$chars, ceil($length/strlen($x)) )),1,$length);
       $length = 4;
       $p2 = substr(str_shuffle(str_repeat($x=$chars, ceil($length/strlen($x)) )),1,$length);
       $length = 4;
       $p3 = substr(str_shuffle(str_repeat($x=$chars, ceil($length/strlen($x)) )),1,$length);
       $length = 4;
       $p4 = substr(str_shuffle(str_repeat($x=$chars, ceil($length/strlen($x)) )),1,$length);
       $length = 12;
       $p5 = substr(str_shuffle(str_repeat($x=$chars, ceil($length/strlen($x)) )),1,$length);
       return $p1."-".$p2."-".$p3."-".$p4."-".$p5;
}
        $jobid = generateRandomJobId();
		$port = rand(5000,5999);
        $checkport = $con->prepare('SELECT COUNT(*) FROM tokens WHERE token=:token AND passedplacelauncher=:passed');
        $checkport->bindParam(':token', $token);
	    $checkport->bindParam(':passed', $okbruh);
        $checkport->execute();
	    $okbrahh = $checkport->fetchColumn();
		if ($okbrahh == 1) {
			$port = rand(5000,5999); // great heavens if this ever happens report to me
                        die("How did we get here?");
		} else if ($okbrahh == 0) {
					$RCCServiceSoap = new Roblox\Grid\Rcc\RCCServiceSoap("127.0.0.1", 64989);
        $script = '
------------------- UTILITY FUNCTIONS --------------------------


function waitForChild(parent, childName)
	while true do
		local child = parent:findFirstChild(childName)
		if child then
			return child
		end
		parent.ChildAdded:wait()
	end
end

-----------------------------------END UTILITY FUNCTIONS -------------------------

-----------------------------------"CUSTOM" SHARED CODE----------------------------------

pcall(function() settings().Network.UseInstancePacketCache = true end)
pcall(function() settings().Network.UsePhysicsPacketCache = true end)
--pcall(function() settings()["Task Scheduler"].PriorityMethod = Enum.PriorityMethod.FIFO end)
pcall(function() settings()["Task Scheduler"].PriorityMethod = Enum.PriorityMethod.AccumulatedError end)

--settings().Network.PhysicsSend = 1 -- 1==RoundRobin
--settings().Network.PhysicsSend = Enum.PhysicsSendMethod.ErrorComputation2
settings().Network.PhysicsSend = Enum.PhysicsSendMethod.TopNErrors
settings().Network.ExperimentalPhysicsEnabled = true
settings().Network.WaitingForCharacterLogRate = 100
pcall(function() settings().Diagnostics:LegacyScriptMode() end)

-----------------------------------START GAME SHARED SCRIPT------------------------------

local assetId = '. $placeid .' -- might be able to remove this now

local scriptContext = game:GetService("ScriptContext")
pcall(function() scriptContext:AddStarterScript(37801172) end)
scriptContext.ScriptsDisabled = true

game:SetPlaceID(assetId, false)
game:GetService("ChangeHistoryService"):SetEnabled(false)

-- establish this peer as the Server
local ns = game:GetService("NetworkServer")

if url~=nil then
	pcall(function() game:GetService("Players"):SetAbuseReportUrl(url .. "/AbuseReport/InGameChatHandler.ashx") end)
	pcall(function() game:GetService("ScriptInformationProvider"):SetAssetUrl(url .. "/Asset/") end)
	pcall(function() game:GetService("ContentProvider"):SetBaseUrl(url .. "/") end)
	pcall(function() game:GetService("Players"):SetChatFilterUrl(url .. "/Game/ChatFilter.ashx") end)

	game:GetService("BadgeService"):SetPlaceId("1818")

	game:GetService("BadgeService"):SetIsBadgeLegalUrl("")
	game:GetService("InsertService"):SetBaseSetsUrl(url .. "/Game/Tools/InsertAsset.ashx?nsets=10&type=base")
	game:GetService("InsertService"):SetUserSetsUrl(url .. "/Game/Tools/InsertAsset.ashx?nsets=20&type=user&userid=%d")
	game:GetService("InsertService"):SetCollectionUrl(url .. "/Game/Tools/InsertAsset.ashx?sid=%d")
	game:GetService("InsertService"):SetAssetUrl(url .. "/Asset/?id=%d")
	game:GetService("InsertService"):SetAssetVersionUrl(url .. "/Asset/?assetversionid=%d")
	
	pcall(function() loadfile(url .. "/Game/LoadPlaceInfo.ashx?PlaceId=" .. placeId)() end)
	
	-- pcall(function() 
	--			if access then
	--				loadfile(url .. "/Game/PlaceSpecificScript.ashx?PlaceId=" .. placeId .. "&" .. access)()
	--			end
	--		end)
end

--pcall(function() game:GetService("NetworkServer"):SetIsPlayerAuthenticationRequired(true) end)
settings().Diagnostics.LuaRamLimit = 0
--settings().Network:SetThroughputSensitivity(0.08, 0.01)
--settings().Network.SendRate = 35
--settings().Network.PhysicsSend = 0  -- 1==RoundRobin


game:GetService("Players").PlayerAdded:connect(function(player)
	print("Player " .. player.userId .. " added")
end)

game:GetService("Players").PlayerRemoving:connect(function(player)
	print("Player " .. player.userId .. " leaving")
end)

if placeId~=nil and url~=nil then
	-- yield so that file load happens in the heartbeat thread
	wait()
	
	-- load the game
	game:Load(url .. "/asset/?id=" .. placeId)
end

-- Now start the connection
ns:Start('. $port .')


scriptContext:SetTimeout(10)
scriptContext.ScriptsDisabled = false



------------------------------END START GAME SHARED SCRIPT--------------------------



-- StartGame -- 
game:GetService("RunService"):Run()
';
        $job = new Roblox\Grid\Rcc\Job($jobid, 9999999999); // pls only set to this amount WHEN ur hosting a gameserver when ur rendering do like 10 minutes
        $funny = new Roblox\Grid\Rcc\ScriptExecution("Script", $script);
        $result = $RCCServiceSoap->BatchJob($job, $funny);
	    $sendthatjob = $con->prepare('INSERT INTO jobs (jobid, placeid, port, ip) VALUES (:jobid, :placeid, :port, :ip)');
	    $sendthatjob->bindParam(':jobid', $jobid);
	    $sendthatjob->bindParam(':placeid', $placeid); // another temporary thing since we don't have random token generator thing and token table
	    $sendthatjob->bindParam(':port', $port);
		$sendthatjob->bindParam(':ip', $AvailableGameservers[1]);
        $sendthatjob->execute();
	    $response = [
        "jobId" => $jobid,
        "status" => $status,
        "joinScriptUrl" => "http://". $soapcfg['url'] ."/game/join?token=". $token ."&jobid=". $jobid,
        "authenticationUrl" => "http://". $soapcfg['url'] ."/Login/Negotiate.ashx",
        "authenticationTicket" => $token,
        "message" => $allstatus[$status]
        ];
	    echo json_encode($response);
		}
	}
	} else {
		header("Location: /");
	}
}
?>
