#pragma newdecls required

#include <sourcemod>
#include <AdminGroups>

#define GameID "csgo-ze"

//----------------------------------------------------------------------------------------------------
// Purpose:
//----------------------------------------------------------------------------------------------------
public Plugin myinfo =
{
	name         = "StatGroups",
	author       = "zaCade (Original by Jenz)",
	description  = "Grant sourcemod groups based on HLStats ranks",
	version      = "1.2"
};

//----------------------------------------------------------------------------------------------------
// Purpose:
//----------------------------------------------------------------------------------------------------
public void OnAllPluginsLoaded()
{
	AdminGroups_CreateAdminGroup("Ranking-Top10");
	AdminGroups_CreateAdminGroup("Ranking-Top20");
	AdminGroups_CreateAdminGroup("Ranking-Top40");
}

//----------------------------------------------------------------------------------------------------
// Purpose:
//----------------------------------------------------------------------------------------------------
public void OnClientAuthorized(int client, const char[] sAuthID)
{
	int rank;
	if ((rank = RetrieveStatRank(client)) == -1)
		return;

	if (rank <= 10) AdminGroups_GrantAdminGroup(client, "Ranking-Top10");
	if (rank <= 20) AdminGroups_GrantAdminGroup(client, "Ranking-Top20");
	if (rank <= 40) AdminGroups_GrantAdminGroup(client, "Ranking-Top40");
}

//----------------------------------------------------------------------------------------------------
// Purpose:
//----------------------------------------------------------------------------------------------------
stock int RetrieveStatRank(int client)
{
	char sError[512];
	char sQuery[512];

	if (!SQL_CheckConfig("stats"))
	{
		LogError("Could not find database config \"stats\".");
		return -1;
	}

	Database database;
	if ((database = SQL_Connect("stats", true, sError, sizeof(sError))) == null)
	{
		LogError("Connection error: \"%s\".", sError);
		delete database;
		return -1;
	}

	char sSteamID[32];
	if (GetClientAuthId(client, AuthId_Steam2, sSteamID, sizeof(sSteamID)))
		strcopy(sSteamID, sizeof(sSteamID), sSteamID[8]);

	SQL_FormatQuery(database, sQuery, sizeof(sQuery), "SELECT COUNT(*) AS rank FROM hlstats_Players WHERE hlstats_Players.game = '%s' AND hideranking = 0 AND skill > (SELECT skill FROM hlstats_Players JOIN hlstats_PlayerUniqueIds ON hlstats_Players.playerId = hlstats_PlayerUniqueIds.playerId WHERE hlstats_PlayerUniqueIds.game = '%s' AND uniqueId = '%s')", GameID, GameID, sSteamID);

	DBResultSet results;
	if ((results = SQL_Query(database, sQuery)) == null)
	{
		delete database;
		delete results;
		return -1;
	}

	if (!results.FetchRow())
	{
		delete database;
		delete results;
		return -1;
	}

	int rank;
	if ((rank = results.FetchInt(0)) == 0)
	{
		delete database;
		delete results;
		return -1;
	}

	delete database;
	delete results;
	return rank;
}