#pragma semicolon 1

#include <sourcemod>

#include "loghelper.inc"

#pragma newdecls required

int g_iClientConnectionTime[MAXPLAYERS + 1];

public Plugin myinfo =
{
	name         = "PlaytimeReward",
	author       = "Obus + Dogan",
	description  = "reward players with points for playing on the server",
	version      = "1.0.0"
};

public void OnPluginStart()
{
	CreateTimer(30.0, Timer_CheckConnectionTime, _, TIMER_REPEAT);

	HookEvent("player_disconnect", EventHook_PlayerDisconnect, EventHookMode_Post);
}

public void OnPluginEnd()
{
	UnhookEvent("player_disconnect", EventHook_PlayerDisconnect, EventHookMode_Post);
}

public void OnMapStart()
{
	GetTeams();
}

public void EventHook_PlayerDisconnect(Event hEvent, const char[] sName, bool bDontBroadcast)
{
	bool bIsBot = view_as<bool>(hEvent.GetInt("bot"));

	if (bIsBot)
		return;

	int client = GetClientOfUserId(hEvent.GetInt("userid"));

	g_iClientConnectionTime[client] = 0;
}

public Action Timer_CheckConnectionTime(Handle hThis)
{
	for (int i = 1; i <= MaxClients; i++)
	{
		if (!IsValidClient(i))
			continue;

		g_iClientConnectionTime[i] += 30;

		for (int iTime = 1800; iTime <= 36000; iTime += 1800)
		{
			if ((g_iClientConnectionTime[i] % 1800) == 0)
			{
				int iConnectionTimeClamped = g_iClientConnectionTime[i];

				if (iConnectionTimeClamped > 36000)
					iConnectionTimeClamped = 36000;

				char sPlayerEvent[32];
				Format(sPlayerEvent, sizeof(sPlayerEvent), "staying_server_%d", iConnectionTimeClamped / 60);

				LogPlayerEvent(i, "triggered", sPlayerEvent);
				break;
			}
		}
	}
}

stock bool IsValidClient(int client)
{
	return (client >= 1 && client <= MaxClients && IsClientInGame(client) && !IsFakeClient(client));
}