#pragma semicolon 1

#include <sourcemod>
#include <multicolors>

#pragma newdecls required

/* CONVARS */
ConVar g_cvInterval;

/* DATABASE */
Database g_hDatabase;

//----------------------------------------------------------------------------------------------------
// Purpose:
//----------------------------------------------------------------------------------------------------
public Plugin myinfo =
{
	name        = "UNLOZE_Donation_Alert",
	author      = "Neon",
	description = "",
	version     = "1.0",
	url         = "https://steamcommunity.com/id/n3ontm"
}

//----------------------------------------------------------------------------------------------------
// Purpose:
//----------------------------------------------------------------------------------------------------
public void OnPluginStart()
{
	g_cvInterval = CreateConVar("sm_unloze_donation_alert_interval", "60", "", FCVAR_NONE);

	AutoExecConfig();

	char sError[256];
	if (SQL_CheckConfig("xenforo"))
		g_hDatabase = SQL_Connect("xenforo", true, sError, sizeof(sError));

	if (g_hDatabase == null)
		LogError("Could not connect to database: %s", sError);
}

//----------------------------------------------------------------------------------------------------
// Purpose:
//----------------------------------------------------------------------------------------------------
public void OnMapStart()
{
	CreateTimer(g_cvInterval.FloatValue, CheckForNewDonations, INVALID_HANDLE, TIMER_REPEAT|TIMER_FLAG_NO_MAPCHANGE);
}

//----------------------------------------------------------------------------------------------------
// Purpose:
//----------------------------------------------------------------------------------------------------
public Action CheckForNewDonations(Handle timer)
{
	char sDataFile[PLATFORM_MAX_PATH];
	BuildPath(Path_SM, sDataFile, sizeof(sDataFile), "configs/unloze_donation_alert/data.cfg");

	if(!FileExists(sDataFile))
	{
		LogError("Could not find data file: \"%s\"", sDataFile);
		return Plugin_Stop;
	}

	KeyValues Data = new KeyValues("unloze_donation_alert");

	if(!Data.ImportFromFile(sDataFile))
	{
		LogError("Unable to load data file: \"%s\"", sDataFile);
		delete Data;
		return Plugin_Stop;
	}

	if(!Data.JumpToKey("last_processed_donation", false))
	{
		LogError("Unable to find section last_processed_donation: \"%s\"",  sDataFile);
		delete Data;
		return Plugin_Stop;
	}

	int iID;
	iID = Data.GetNum("id", -1);
	if (iID == -1)
	{
		LogError("Unable to ID of last_processed_donation: \"%s\"",  sDataFile);
		delete Data;
		return Plugin_Stop;
	}

	char sQuery[255];
	Format(sQuery, sizeof(sQuery), "SELECT * FROM xf_bdpaygate_log WHERE log_id = %d", iID + 1);
	g_hDatabase.Query(TQueryCB, sQuery, iID + 1);

	delete Data;
	return Plugin_Continue;
}

//----------------------------------------------------------------------------------------------------
// Purpose:
//----------------------------------------------------------------------------------------------------
public void TQueryCB(Database db, DBResultSet results, const char[] error, any data)
{
	int iID = data;

	if (results.RowCount > 0)
	{
		int iField;
		char sLogType[64];
		char sLogDetails[4096];
		results.FetchRow();
		results.FieldNameToNum("log_type", iField);
		results.FetchString(iField, sLogType, sizeof(sLogType));

		if(!StrEqual(sLogType, "accepted"))
		{
			HandleDonation(iID);
			char sQuery[255];
			Format(sQuery, sizeof(sQuery), "SELECT * FROM xf_bdpaygate_log WHERE log_id = %d", iID + 1);
			g_hDatabase.Query(TQueryCB, sQuery, iID + 1);
			return;
		}

		results.FieldNameToNum("log_details", iField);
		results.FetchString(iField, sLogDetails, sizeof(sLogDetails));
		static char sStrings[256][256];
		char sMessage[256];
		char sMessageWhite[256];
		int iStrings = ExplodeString(sLogDetails, "\"", sStrings, 256, 256);

		if (StrContains(sLogDetails, "user_upgrade") != -1)
		{
			for (int i = 0; i < iStrings; i++)
			{
				if (StrContains(sStrings[i], "Account Upgrade:") != -1)
				{
					char sBuffer[256];
					char sUpgrade[256];
					char sName[256];
					strcopy(sBuffer, sizeof(sBuffer), sStrings[i]);

					int iStart = FindCharInString(sBuffer, ':', false);
					strcopy(sBuffer, sizeof(sBuffer), sBuffer[iStart + 2]);
					iStart = FindCharInString(sBuffer, '(', false);
					strcopy(sName, sizeof(sName), sBuffer[iStart + 1]);
					int iLength = strlen(sName);
					sName[iLength-1] = 0;
					SplitString(sBuffer, "(", sUpgrade, sizeof(sUpgrade));
					Format(sMessage, sizeof(sMessage), "{chartreuse}[UNLOZE] {lightblue}%s {white}just bought {lightblue}%s{white}! Thank you for supporting our servers!!!", sName, sUpgrade);
					Format(sMessageWhite, sizeof(sMessageWhite), "%s just bought %s! Thank you for supporting our servers!!!", sName, sUpgrade);

				}
			}
		}
		else if (StrContains(sLogDetails, "gift_upgrade") != -1)
		{
			for (int i = 0; i < iStrings; i++)
			{
				if (StrContains(sStrings[i], "Account Upgrade:") != -1)
				{
					char sBuffer[256];
					char sUpgrade[256];
					char sName[256];
					strcopy(sBuffer, sizeof(sBuffer), sStrings[i]);

					int iStart = FindCharInString(sBuffer, ':', false);
					strcopy(sBuffer, sizeof(sBuffer), sBuffer[iStart + 2]);
					iStart = FindCharInString(sBuffer, '(', false);
					strcopy(sName, sizeof(sName), sBuffer[iStart + 1]);
					int iLength = strlen(sName);
					sName[iLength-1] = 0;
					SplitString(sBuffer, "(", sUpgrade, sizeof(sUpgrade));

					Format(sMessage, sizeof(sMessage), "{chartreuse}[UNLOZE] {lightblue}%s {white}just recieved {lightblue}%s {white}as a gift! Thank you for supporting our servers!!!", sName, sUpgrade);
					Format(sMessageWhite, sizeof(sMessageWhite), "%s just recieved %s as a gift! Thank you for supporting our servers!!!", sName, sUpgrade);
				}
			}
		}

		CPrintToChatAll(sMessage);
		for(int client = 1; client <= MaxClients; client++)
		{
			if(IsClientInGame(client))
			{
				PrintHintText(client, sMessageWhite);
			}
		}

		HandleDonation(iID);
		char sQuery[255];
		Format(sQuery, sizeof(sQuery), "SELECT * FROM xf_bdpaygate_log WHERE log_id = %d", iID + 1);
		g_hDatabase.Query(TQueryCB, sQuery, iID + 1);
	}
}

//----------------------------------------------------------------------------------------------------
// Purpose:
//----------------------------------------------------------------------------------------------------
public void HandleDonation(int iID)
{
	char sDataFile[PLATFORM_MAX_PATH];
	BuildPath(Path_SM, sDataFile, sizeof(sDataFile), "configs/unloze_donation_alert/data.cfg");

	if(!FileExists(sDataFile))
	{
		LogError("Could not find data file: \"%s\"", sDataFile);
		return;
	}

	KeyValues Data = new KeyValues("unloze_donation_alert");

	if(!Data.JumpToKey("last_processed_donation", true))
	{
		LogError("Unable to create section last_processed_donation: \"%s\"",  sDataFile);
		delete Data;
		return;
	}
	Data.SetNum("id", iID);
	Data.Rewind();
	if(!Data.ExportToFile(sDataFile))
	{
		LogError("Unable to export data file: \"%s\"", sDataFile);
		delete Data;
		return;
	}
	delete Data;
}