#pragma semicolon 1

#define DEBUG

#define PLUGIN_AUTHOR "jenz"
#define PLUGIN_VERSION "2.00"

#define MAX_DEFINED_COLORS 128
#define MAX_DEFINED_MATERIALS 128

//taser
#define TASER "weapon_tracers_taser"
#define GLOW "weapon_taser_glow_impact"
#define SOUND_IMPACT "weapons/taser/taser_hit.wav"
#define SOUND_SHOOT "weapons/taser/taser_shoot.wav"

#include <sourcemod>
#include <sdktools>
#include <csgocolors>
#include <sdkhooks>
#include <clientprefs>
#include <emitsoundany>

#undef REQUIRE_EXTENSIONS
#tryinclude <dhooks>
#define REQUIRE_EXTENSIONS

#pragma newdecls required
//potentially 1024 bits
char g_cStorestats[MAXPLAYERS][526];
bool g_bZeusOwner[MAXPLAYERS];
float g_fLastAngles[MAXPLAYERS + 1][3];
int g_iTracerpref[MAXPLAYERS];
int g_iPlayerRank[MAXPLAYERS + 1];
int g_iPlayerPoints[MAXPLAYERS + 1];
int g_iTEsends[MAXPLAYERS];
int g_iBeam = -1;
int g_iPlayerCount;
int g_iPlayerCountTop10;
int g_iPlayerArrayTop10[MAXPLAYERS];
int g_iPlayerArray[MAXPLAYERS];
int g_iStoreColors[MAXPLAYERS][3];
bool g_bStoreColorbool[MAXPLAYERS];

public Plugin myinfo = 
{
	name = "Unloze Tracers based on zeustracers",
	author = PLUGIN_AUTHOR,
	description = "Grants sprayTracers based on clients ranking",
	version = PLUGIN_VERSION,
	url = "https://forums.alliedmods.net/showthread.php?p=2501632"
};

//Startup
public APLRes AskPluginLoad2(Handle myself, bool late, char[] error, int err_max)
{	
	return APLRes_Success;
}

public void OnPluginStart()
{
	//Reg Cmds
	RegConsoleCmd("sm_tracers", Cmd_Tracer, "enable/ disable tracers");
	
	//mysql
	SQL_StartConnection();
	
	AddTempEntHook("Shotgun Shot", Hook_BulletShot);
	HookEvent("bullet_impact", Event_OnBulletImpact);
	HookEvent("round_start", Event_RoundStart);
}

public void Event_RoundStart(Handle event, const char[] name, bool dontBroadcast)
{
	for (int i = 0; i < MaxClients; i++)
	{
		if (IsValidClient(i) && IsPlayerAlive(i))
		{
			g_iTEsends[i] = 0;
		}
	}
}

public void OnMapStart()
{
	g_iBeam = PrecacheModel("materials/unloze_tracers/xbeam.vmt");
	AddFileToDownloadsTable("materials/unloze_tracers/xbeam.vmt");
	AddFileToDownloadsTable("materials/unloze_tracers/xbeam.vtf");
	PrecacheEffect("ParticleEffect");
	PrecacheParticleEffect(TASER);
	PrecacheParticleEffect(GLOW);
	PrecacheSound(SOUND_IMPACT);
	PrecacheSound(SOUND_SHOOT);
}

void PrecacheEffect(const char[] sEffectName)
{
	static int table = INVALID_STRING_TABLE;
	
	if (table == INVALID_STRING_TABLE)
		table = FindStringTable("EffectDispatch");
		
	bool save = LockStringTables(false);
	AddToStringTable(table, sEffectName);
	LockStringTables(save);
}

void PrecacheParticleEffect(const char[] sEffectName)
{
	static int table = INVALID_STRING_TABLE;
	
	if (table == INVALID_STRING_TABLE)
		table = FindStringTable("ParticleEffectNames");
	
	bool save = LockStringTables(false);
	AddToStringTable(table, sEffectName);
	LockStringTables(save);
}

public Action Cmd_Tracer(int client, int args)
{
	Menu menu = new Menu(MenuHandler1);
	menu.SetTitle("UNLOZE tracers are unlocked through !shop");
	menu.AddItem("", "Toggle Tracer Visibility");
	if (StrContains(g_cStorestats[client], "k") >= 0)
	{
		menu.AddItem("", "Zeus tracers");
	}
	if (StrContains(g_cStorestats[client], "§") >= 0)
	{
		menu.AddItem("255 255 0", "Yellow Tracers");
	}
	if (StrContains(g_cStorestats[client], "@") >= 0)
	{
		menu.AddItem("0 0 255", "Blue Tracers");
	}
	if (StrContains(g_cStorestats[client], "£") >= 0)
	{
		menu.AddItem("0 255 0", "Green Tracers");
	}
	if (StrContains(g_cStorestats[client], "$") >= 0)
	{
		menu.AddItem("255 0 0", "Red Tracers");
	}
	if (StrContains(g_cStorestats[client], "€") >= 0)
	{
		menu.AddItem("255 215 0", "Gold Tracers");
	}
	if (StrContains(g_cStorestats[client], "(") >= 0)
	{
		menu.AddItem("0 255 255", "cyan Tracers");
	}
	menu.ExitButton = true;
	menu.Display(client, 0);
	return Plugin_Handled;
}


public int MenuHandler1(Menu menu, MenuAction action, int param1, int choice)
{
	char info[256];
	menu.GetItem(choice, info, sizeof(info));
	if (action == MenuAction_Cancel)
	{
		//PrintToServer("Client %d's menu was cancelled.  Reason: %d", param1, choice);
	}
	
	else if (action == MenuAction_End)
	{
		delete menu;
	}
	else if (action == MenuAction_Select)
	{
		if (choice == 0)
		{
			g_bZeusOwner[param1] = false;
			g_bStoreColorbool[param1] = false;
			static char SID[32];
			GetClientAuthId(param1, AuthId_Steam2, SID, sizeof(SID));
			if (g_iTracerpref[param1] == 0)
			{
				g_iTracerpref[param1] = 1;
				PrintToChat(param1, "Disabled tracers"); 
			}
			else
			{
				g_iTracerpref[param1] = 0;
				PrintToChat(param1, "Enabled tracers");
			}
			ClientCount(); 
			tracerprefMYSQL(param1);
			return 0;
		}
		else if (choice == 1)
		{
			g_bZeusOwner[param1] = true;
			g_bStoreColorbool[param1] = false;
		}
		else if (choice > 1)
		{
			char l_cColorPref[256];
			g_bStoreColorbool[param1] = true;
			g_bZeusOwner[param1] = false;
			Format(l_cColorPref, sizeof(l_cColorPref), info);
			char sPart[3][526];
			ExplodeString(l_cColorPref, " ", sPart, 3, 526);
			g_iStoreColors[param1][0] = StringToInt(sPart[0]);
			g_iStoreColors[param1][1] = StringToInt(sPart[1]);
			g_iStoreColors[param1][2] = StringToInt(sPart[2]);
			InsertTracerPrefMYSQL(param1, l_cColorPref);
		}
	}
	ClientCount(); 
	return 0;
}


public Action Event_OnBulletImpact(Event event, const char[] name, bool dontBroadcast)
{		
	int client = GetClientOfUserId(event.GetInt("userid"));
	//unnecesary checks but eh
	if (!IsClientInGame(client) || IsFakeClient(client) || g_iPlayerArray[0] == '\0' || g_iPlayerCount < 1)
	{
		return Plugin_Handled;
	}
	if (g_iTracerpref[client] == 1)
	{
		return Plugin_Handled;
	}
	//bought tracers for 25000 tokens in the shop if true
	if (!g_bZeusOwner[client] && !g_bStoreColorbool[client])
	{
		//making sure if not bought from shop that atleast rank 32 and 5000 points
		if (g_iPlayerRank[client] > 32 || g_iPlayerPoints[client] < 5000)
		{
			//PrintToChatAll("g_cStorestats client %N: %s", client, g_cStorestats[client]);
			return Plugin_Handled;
		}
	}
	++g_iTEsends[client];
	if (g_iTEsends[client] < 2)
	{
		return Plugin_Handled;
	}
	g_iTEsends[client] = 0;
	
	float impact_pos[3];
	float  fPosition[3], fImpact[3], fDifference[3];
	float muzzle_pos[3], camera_pos[3];
	float pov_pos[3];
	int l_iStoreColors[3];
	
	GetClientEyePosition(client, fPosition);
	impact_pos[0] = event.GetFloat("x");
	impact_pos[1] = event.GetFloat("y");
	impact_pos[2] = event.GetFloat("z");
	fImpact[0] = GetEventFloat (event, "x");
	fImpact[1] = GetEventFloat (event, "y");
	fImpact[2] = GetEventFloat (event, "z");
	
	GetWeaponAttachmentPosition(client, "muzzle_flash", muzzle_pos);
	GetWeaponAttachmentPosition(client, "camera_buymenu", camera_pos);
	
	//Create an offset for first person
	pov_pos[0] = muzzle_pos[0] - camera_pos[0];
	pov_pos[1] = muzzle_pos[1] - camera_pos[1];
	pov_pos[2] = muzzle_pos[2] - camera_pos[2] + 0.1;
	ScaleVector(pov_pos, 0.4);
	SubtractVectors(muzzle_pos, pov_pos, pov_pos);
	
	//Move the beam a bit forward so it isn't too close for first person
	float distance = GetVectorDistance(pov_pos, impact_pos);
	float percentage = 0.2 / (distance / 100);
	pov_pos[0] = pov_pos[0] + ((impact_pos[0] - pov_pos[0]) * percentage);
	pov_pos[1] = pov_pos[1] + ((impact_pos[1] - pov_pos[1]) * percentage);
	pov_pos[2] = pov_pos[2] + ((impact_pos[2] - pov_pos[2]) * percentage);
	

	float  fDistance = GetVectorDistance(fPosition, fImpact);
	float  fPercent = (0.4 / (fDistance / 100.0));

	fDifference[0] = fPosition[0] + ((fImpact[0] - fPosition[0]) * fPercent);
	fDifference[1] = fPosition[1] + ((fImpact[1] - fPosition[1]) * fPercent) - 0.08;
	fDifference[2] = fPosition[2] + ((fImpact[2] - fPosition[2]) * fPercent);
	
	//MASK_SOLID_BRUSHONLY
	Handle trace = TR_TraceRayFilterEx(fDifference, fImpact, MASK_SHOT, RayType_EndPoint, Bool_TraceFilterPlayers);
	TR_GetEndPosition(fImpact, trace); 
	CloseHandle(trace);
	
	if (g_bZeusOwner[client])
	{
		if (g_iPlayerArrayTop10[0] == '\0' || g_iPlayerCountTop10 < 1)
		{
			return Plugin_Handled;
		}
		TE_DispatchEffect(TASER, impact_pos, pov_pos, g_fLastAngles[client]);
		TE_Send(g_iPlayerArrayTop10, g_iPlayerCountTop10);
		
		//Display the particle to everyone else under the normal position
		TE_DispatchEffect(TASER, impact_pos, muzzle_pos, g_fLastAngles[client]);
		TE_Send(g_iPlayerArray, g_iPlayerCount);
		
		//Move the impact glow a bit out so it doesn't clip the wall
		impact_pos[0] = impact_pos[0] + ((pov_pos[0] - impact_pos[0]) * percentage);
		impact_pos[1] = impact_pos[1] + ((pov_pos[1] - impact_pos[1]) * percentage);
		impact_pos[2] = impact_pos[2] + ((pov_pos[2] - impact_pos[2]) * percentage);
		
		TE_DispatchEffect(GLOW, impact_pos, impact_pos);
		TE_Send(g_iPlayerArrayTop10, g_iPlayerCountTop10);
		
		TE_DispatchEffect(GLOW, impact_pos, impact_pos);
		TE_Send(g_iPlayerArray, g_iPlayerCount);
		
		//play taser sounds to clients
		EmitSound(g_iPlayerArrayTop10, g_iPlayerCountTop10, SOUND_SHOOT, client, SNDCHAN_WEAPON, SNDLEVEL_NORMAL, SND_NOFLAGS, 0.15, SNDPITCH_NORMAL);
		EmitSound(g_iPlayerArrayTop10, g_iPlayerCountTop10, SOUND_IMPACT, client, SNDCHAN_WEAPON, SNDLEVEL_NORMAL, SND_NOFLAGS, 0.15, SNDPITCH_NORMAL);
		EmitSoundToClient(client, SOUND_SHOOT, client, SNDCHAN_WEAPON, SNDLEVEL_NORMAL, SND_NOFLAGS, 0.15, SNDPITCH_NORMAL);
		EmitSoundToClient(client, SOUND_IMPACT, client, SNDCHAN_WEAPON, SNDLEVEL_NORMAL, SND_NOFLAGS, 0.15, SNDPITCH_NORMAL);
		return Plugin_Handled;
	}
	else if (g_bStoreColorbool[client])
	{
		l_iStoreColors[0] = g_iStoreColors[client][0];
		l_iStoreColors[1] = g_iStoreColors[client][1];
		l_iStoreColors[2] = g_iStoreColors[client][2];
	}
	if (g_iPlayerRank[client] > 32)
	{
		TE_SetupBeamPoints(fDifference, fImpact, g_iBeam, 0, 0, 0, 0.6, 4.0, 4.0, 1, 1.1, {192, 192, 192, 105}, 1);
		TE_Send(g_iPlayerArray, g_iPlayerCount);
		return Plugin_Handled;
	}
	//red
	else if (g_iPlayerRank[client] > 29 || colorIndex(l_iStoreColors, 255, 0, 0))
	{
		TE_SetupBeamPoints(fDifference, fImpact, g_iBeam, 0, 0, 0, 0.6, 4.0, 4.0, 1, 1.1, {255, 0, 0, 105}, 1);
		TE_Send(g_iPlayerArray, g_iPlayerCount);
		return Plugin_Handled;
	}
	else if (g_iPlayerRank[client] > 27)
	{
		TE_SetupBeamPoints(fDifference, fImpact, g_iBeam, 0, 0, 0, 0.6, 4.0, 4.0, 1, 1.1, {255, 77, 0, 105}, 1);
		TE_Send(g_iPlayerArray, g_iPlayerCount);
		return Plugin_Handled;
	}
	//yellow
	else if (g_iPlayerRank[client] > 25 || colorIndex(l_iStoreColors, 255, 255, 0))
	{
		TE_SetupBeamPoints(fDifference, fImpact, g_iBeam, 0, 0, 0, 0.6, 4.0, 4.0, 1, 1.1, {255, 255, 0, 105}, 1);
		TE_Send(g_iPlayerArray, g_iPlayerCount);
		return Plugin_Handled;
	}
	//blue
	else if (colorIndex(l_iStoreColors, 0, 0, 255))
	{
		TE_SetupBeamPoints(fDifference, fImpact, g_iBeam, 0, 0, 0, 0.6, 4.0, 4.0, 1, 1.1, {0, 0, 255, 105}, 1);
		TE_Send(g_iPlayerArray, g_iPlayerCount);
		return Plugin_Handled;
	}
	//gold 
	else if (colorIndex(l_iStoreColors, 255, 215, 0))
	{
		TE_SetupBeamPoints(fDifference, fImpact, g_iBeam, 0, 0, 0, 0.6, 4.0, 4.0, 1, 1.1, {255, 215, 0, 105}, 1);
		TE_Send(g_iPlayerArray, g_iPlayerCount);
		return Plugin_Handled;
	}
	//cyan 0 255 255
	else if (colorIndex(l_iStoreColors, 0, 255, 255))
	{
		TE_SetupBeamPoints(fDifference, fImpact, g_iBeam, 0, 0, 0, 0.6, 4.0, 4.0, 1, 1.1, {0, 255, 255, 105}, 1);
		TE_Send(g_iPlayerArray, g_iPlayerCount);
		return Plugin_Handled;
	}
	else if (g_iPlayerRank[client] > 23)
	{
		TE_SetupBeamPoints(fDifference, fImpact, g_iBeam, 0, 0, 0, 0.6, 4.0, 4.0, 1, 1.1, {35, 142, 35, 105}, 1);
		TE_Send(g_iPlayerArray, g_iPlayerCount);
		return Plugin_Handled;
	}
	else if (g_iPlayerRank[client] > 21)
	{
		TE_SetupBeamPoints(fDifference, fImpact, g_iBeam, 0, 0, 0, 0.6, 4.0, 4.0, 1, 1.1, {128, 128, 0, 105}, 1);
		TE_Send(g_iPlayerArray, g_iPlayerCount);
		return Plugin_Handled;
	}
	else if (g_iPlayerRank[client] > 18)
	{
		TE_SetupBeamPoints(fDifference, fImpact, g_iBeam, 0, 0, 0, 0.6, 4.0, 4.0, 1, 1.1, {64, 224, 208, 105}, 1);
		TE_Send(g_iPlayerArray, g_iPlayerCount);
		return Plugin_Handled;
	}
	else if (g_iPlayerRank[client] > 15)
	{
		TE_SetupBeamPoints(fDifference, fImpact, g_iBeam, 0, 0, 0, 0.6, 4.0, 4.0, 1, 1.1, {0, 128, 128, 105}, 1);
		TE_Send(g_iPlayerArray, g_iPlayerCount);
		return Plugin_Handled;
	}
	else if (g_iPlayerRank[client] > 13)
	{
		TE_SetupBeamPoints(fDifference, fImpact, g_iBeam, 0, 0, 0, 0.6, 4.0, 4.0, 1, 1.1, {240, 248, 255, 105}, 1);
		TE_Send(g_iPlayerArray, g_iPlayerCount);
		return Plugin_Handled;
	}
	else if (g_iPlayerRank[client] > 12)
	{
		TE_SetupBeamPoints(fDifference, fImpact, g_iBeam, 0, 0, 0, 0.6, 4.0, 4.0, 1, 1.1, {128, 0, 128, 105}, 1);
		TE_Send(g_iPlayerArray, g_iPlayerCount);
		return Plugin_Handled;
	}
	else if (g_iPlayerRank[client] > 9)
	{
		TE_SetupBeamPoints(fDifference, fImpact, g_iBeam, 0, 0, 0, 0.6, 4.0, 4.0, 1, 1.1, {148, 0, 211, 105}, 1);
		TE_Send(g_iPlayerArray, g_iPlayerCount);	
		return Plugin_Handled;			
	}
	//green
	else if (g_iPlayerRank[client] > 6 || colorIndex(l_iStoreColors, 255, 255, 0))
	{
		TE_SetupBeamPoints(fDifference, fImpact, g_iBeam, 0, 0, 0, 0.6, 4.0, 4.0, 1, 1.1, {0, 255, 0, 105}, 1);		
		TE_Send(g_iPlayerArray, g_iPlayerCount);	
		return Plugin_Handled;			
	}
	else if (g_iPlayerRank[client] > 3)
	{
		TE_SetupBeamPoints(fDifference, fImpact, g_iBeam, 0, 0, 0, 0.6, 4.0, 4.0, 1, 1.1, {218, 112, 214, 105}, 1);
		TE_Send(g_iPlayerArray, g_iPlayerCount);
		return Plugin_Handled;
	}
	else if (g_iPlayerRank[client] >= 0)
	{
		//Display the particle to first person 
		TE_DispatchEffect(TASER, impact_pos, pov_pos, g_fLastAngles[client]);
		TE_Send(g_iPlayerArrayTop10, g_iPlayerCountTop10);
		
		//Display the particle to everyone else under the normal position
		TE_DispatchEffect(TASER, impact_pos, muzzle_pos, g_fLastAngles[client]);
		TE_Send(g_iPlayerArray, g_iPlayerCount);
		
		//Move the impact glow a bit out so it doesn't clip the wall
		impact_pos[0] = impact_pos[0] + ((pov_pos[0] - impact_pos[0]) * percentage);
		impact_pos[1] = impact_pos[1] + ((pov_pos[1] - impact_pos[1]) * percentage);
		impact_pos[2] = impact_pos[2] + ((pov_pos[2] - impact_pos[2]) * percentage);
		
		TE_DispatchEffect(GLOW, impact_pos, impact_pos);
		TE_Send(g_iPlayerArrayTop10, g_iPlayerCountTop10);
		TE_DispatchEffect(GLOW, impact_pos, impact_pos);
		TE_Send(g_iPlayerArray, g_iPlayerCount);
		
		//play taser sounds to clients SNDCHAN_STATIC
		EmitSound(g_iPlayerArrayTop10, g_iPlayerCountTop10, SOUND_SHOOT, client, SNDCHAN_WEAPON, SNDLEVEL_NORMAL, SND_NOFLAGS, 0.15, SNDPITCH_NORMAL);
		EmitSound(g_iPlayerArrayTop10, g_iPlayerCountTop10, SOUND_IMPACT, client, SNDCHAN_WEAPON, SNDLEVEL_NORMAL, SND_NOFLAGS, 0.15, SNDPITCH_NORMAL);
		EmitSoundToClient(client, SOUND_SHOOT, client, SNDCHAN_WEAPON, SNDLEVEL_NORMAL, SND_NOFLAGS, 0.15, SNDPITCH_NORMAL);
		EmitSoundToClient(client, SOUND_IMPACT, client, SNDCHAN_WEAPON, SNDLEVEL_NORMAL, SND_NOFLAGS, 0.15, SNDPITCH_NORMAL);
		return Plugin_Handled;
	}
	return Plugin_Handled;
}


public Action Hook_BulletShot(const char[] te_name, const int[] Players, int numClients, float delay)
{
	
	int client = TE_ReadNum("m_iPlayer") + 1;
	
	float origin[3];
	TE_ReadVector("m_vecOrigin", origin);
	g_fLastAngles[client][0] = TE_ReadFloat("m_vecAngles[0]");
	g_fLastAngles[client][1] = TE_ReadFloat("m_vecAngles[1]");
	g_fLastAngles[client][2] = 0.0;
	
	float impact_pos[3];
	Handle trace = TR_TraceRayFilterEx(origin, g_fLastAngles[client], MASK_SHOT, RayType_Infinite, TR_DontHitSelf, client);
	if (TR_DidHit(trace))
	{
		TR_GetEndPosition(impact_pos, trace);
	}
	delete trace;
	return Plugin_Continue;
}

public bool TR_DontHitSelf(int entity, int mask, any data)
{
	if (entity == data) 
		return false;
	return true;
}

void GetWeaponAttachmentPosition(int client, const char[] attachment, float pos[3])
{
	if (!attachment[0])
		return;
		
	int entity = CreateEntityByName("info_target");
	DispatchSpawn(entity);
	
	int weapon;
	
	if ((weapon = GetEntPropEnt(client, Prop_Send, "m_hActiveWeapon")) == -1)
		return;
	
	if ((weapon = GetEntPropEnt(weapon, Prop_Send, "m_hWeaponWorldModel")) == -1)
		return;
		
	SetVariantString("!activator");
	AcceptEntityInput(entity, "SetParent", weapon, entity, 0);
	
	SetVariantString(attachment); 
	AcceptEntityInput(entity, "SetParentAttachment", weapon, entity, 0);
	
	TeleportEntity(entity, NULL_VECTOR, NULL_VECTOR, NULL_VECTOR);
	GetEntPropVector(entity, Prop_Data, "m_vecAbsOrigin", pos);
	AcceptEntityInput(entity, "kill");
}

void TE_DispatchEffect(const char[] particle, const float pos[3], const float endpos[3], const float angles[3] = NULL_VECTOR)
{
	TE_Start("EffectDispatch");
	TE_WriteFloatArray("m_vStart.x", pos, 3);
	TE_WriteFloatArray("m_vOrigin.x", endpos, 3);
	TE_WriteVector("m_vAngles", angles);
	TE_WriteNum("m_nHitBox", GetParticleEffectIndex(particle));
	TE_WriteNum("m_iEffectName", GetEffectIndex("ParticleEffect"));	
}


int GetParticleEffectIndex(const char[] sEffectName)
{
	static int table = INVALID_STRING_TABLE;

	if (table == INVALID_STRING_TABLE)
		table = FindStringTable("ParticleEffectNames");

	int iIndex = FindStringIndex(table, sEffectName);

	if (iIndex != INVALID_STRING_INDEX)
		return iIndex;

	return 0;
}


int GetEffectIndex(const char[] sEffectName)
{
	static int table = INVALID_STRING_TABLE;

	if (table == INVALID_STRING_TABLE)
		table = FindStringTable("EffectDispatch");

	int iIndex = FindStringIndex(table, sEffectName);

	if (iIndex != INVALID_STRING_INDEX)
		return iIndex;

	return 0;
}

public void OnClientPostAdminCheck(int client)
{
	if (client > 0 && client <= MaxClients && IsClientInGame(client))
	{
		g_bStoreColorbool[client] = false;
		CheckFlagsMYSQL(client);
		tracerprefMYSQLpostadmin(client);
		CheckMYSQLTracerColorPref(client);
		g_iPlayerRank[client] = CheckMYSQL(client);
		g_iPlayerPoints[client] = CheckMYSQLPoints(client);
		g_iTEsends[client] = 0;
		g_bZeusOwner[client] = false;
		if (StrContains(g_cStorestats[client], "k") >= 0 && !g_bStoreColorbool[client])
		{
			g_bZeusOwner[client] = true;	
		}
		ClientCount();
	}
}

public void OnClientDisconnect_Post(int client)
{
	ClientCount();
}

public void OnClientDisconnect (int client)
{
	Format(g_cStorestats[client], sizeof(g_cStorestats), "");
	g_iPlayerRank[client] = 0;
	g_iPlayerPoints[client] = 0;
	g_iTEsends[client] = 0;
	g_bZeusOwner[client] = false;
	g_bStoreColorbool[client] = false;
	g_iTracerpref[client] = 0;
	g_iStoreColors[client][0] = 0;
	g_iStoreColors[client][1] = 0;
	g_iStoreColors[client][2] = 0;
}

public bool Bool_TraceFilterPlayers(int entity, int contentsMask, any client) 
{
	return !entity || entity > MaxClients;
}

public int CheckMYSQL(int client)
{
	if (client < 1 || client > MaxClients)
	{
		return ThrowNativeError(SP_ERROR_NATIVE, "Invalid client index (%d)", client);
	}
	if (!IsClientConnected(client))
	{
		return ThrowNativeError(SP_ERROR_NATIVE, "Client %d is not connected", client);
	}
	
	char error[255];
	Database db;
	if (SQL_CheckConfig("stats"))
	{
		db = SQL_Connect("stats", true, error, sizeof(error));
	}
	if (db == null)
	{
		PrintToChat(client, "{green}[Unloze] {white}Error! Could not connect to MYSQL-DB!");
		delete db;
		return -1;
	}
	char sSID[64];
	GetClientAuthId(client, AuthId_Steam2, sSID, sizeof(sSID));
	char sQuery[512];
	
	strcopy(sSID, sizeof(sSID), sSID[8]); //matching up with hlstats_PlayerUniqueIds
	Format(sQuery, sizeof(sQuery), "SELECT COUNT(*) AS rank FROM hlstats_Players WHERE hlstats_Players.game = 'csgo-ze' AND hideranking = 0 AND skill > (SELECT skill from hlstats_Players JOIN hlstats_PlayerUniqueIds ON hlstats_Players.playerId = hlstats_PlayerUniqueIds.playerId WHERE uniqueId = '%s' AND hlstats_PlayerUniqueIds.game = 'csgo-ze')", sSID);
	
	DBResultSet rs;
	
	if ((rs = SQL_Query(db, sQuery)) == null)
	{
		
		delete db;
		delete rs;
		return -1;
	}
	
	
	int iCollected;
	
	if (!(rs.RowCount > 0))
	{
		iCollected = 0;
	}
	else
	{
		int iField;
		rs.FetchRow();
		rs.FieldNameToNum("collected", iField);
		iCollected = rs.FetchInt(iField);
	}
	delete rs;
	delete db;
	return iCollected;
} 


public void InsertTracerPrefMYSQL(int client, char[] colornumber)
{
	char error[255];
	Database db; 
	//the points not related to hlstats are stored together with tracer prefferences but have
	//their own table
	if (SQL_CheckConfig("unloze_tracerpref"))
	{
		db = SQL_Connect("unloze_tracerpref", true, error, sizeof(error));
	}
	if (db == null)
	{
		PrintToChat(client, "{green}[Unloze] {white}Error! Could not connect to MYSQL-DB!");
		delete db;
		return;
	}
	char sSID[64];
	GetClientAuthId(client, AuthId_Steam2, sSID, sizeof(sSID));
	char sQuery[512];
	Format(sQuery, sizeof(sQuery), "INSERT INTO `unloze_tracerprefColor` (`steam_id`, `Color`) VALUES ('%s','%s') ON DUPLICATE KEY UPDATE `Color` = '%s'", sSID, colornumber, colornumber);
	SQL_TQuery(db, DummyCallbackSimple, sQuery);
	delete db;
}


/*neon idea */
public int CheckMYSQLPoints (int client)
{
	if (client < 1 || client > MaxClients)
	{
		return ThrowNativeError(SP_ERROR_NATIVE, "Invalid client index (%d)", client);
	}
	if (!IsClientConnected(client))
	{
		return ThrowNativeError(SP_ERROR_NATIVE, "Client %d is not connected", client);
	}
	
	
	char error[255];
	Database db;
	if (SQL_CheckConfig("levels"))
	{
		db = SQL_Connect("levels", true, error, sizeof(error));
	}
	if (db == null)
	{
		PrintToChat(client, "{green}[Unloze] {white}Error! Could not connect to MYSQL-DB!");
		delete db;
		return -1;
	}
	char sSID[64];
	GetClientAuthId(client, AuthId_Steam2, sSID, sizeof(sSID));
	strcopy(sSID, sizeof(sSID), sSID[8]); //matching up with hlstats_PlayerUniqueIds
	char sQuery[255];
	Format(sQuery, sizeof(sQuery), "SELECT skill from hlstats_Players JOIN hlstats_PlayerUniqueIds ON hlstats_Players.playerId = hlstats_PlayerUniqueIds.playerId WHERE uniqueId = '%s' AND hlstats_PlayerUniqueIds.game = 'csgo-ze'", sSID);

	DBResultSet rs;
	
	if ((rs = SQL_Query(db, sQuery)) == null)
	{
		//PrintToConsole(client, "[Unloze] Failed sQuery: %s", sQuery);
		delete db;
		delete rs;
		return -1;
	}
	//PrintToConsole(client, "[Unloze] Success sQuery: %s", sQuery);
	
	
	int iCollected;
	
	if (!(rs.RowCount > 0))
	{
		iCollected = 0;
	}
	else
	{
		int iField;
		rs.FetchRow();
		rs.FieldNameToNum("collected", iField);
		iCollected = rs.FetchInt(iField);
	}
	delete rs;
	delete db;
	return iCollected;
} 

public void SQL_StartConnection()
{
	char error[255];
	Database db;
	if (SQL_CheckConfig("unloze_tracerpref")) 
	{
		db = SQL_Connect("unloze_tracerpref", true, error, sizeof(error));
	}
	if (db == null)
	{
		CPrintToChatAll("{green}[Unloze] {white}Error! Could not connect to MYSQL-DB!");
		delete db;
		return;
	}
	//create tables
	char sQuery[255];
	Format(sQuery, sizeof(sQuery), "CREATE TABLE IF NOT EXISTS `unloze_tracerpref` (`steam_id` VARCHAR(254) NOT NULL, `disabled` VARCHAR(254) NOT NULL, PRIMARY KEY (`steam_id`))");
	SQL_TQuery(db, DummyCallbackSimple, sQuery);
	Format(sQuery, sizeof(sQuery), "CREATE TABLE IF NOT EXISTS `unloze_tracerprefColor` (`steam_id` VARCHAR(254) NOT NULL, `Color` VARCHAR(254) NOT NULL, PRIMARY KEY (`steam_id`))");
	SQL_TQuery(db, DummyCallbackSimple, sQuery);
	
	delete db;
}

public void tracerprefMYSQL(int client)
{
	char error[255];
	Database db;
	if (SQL_CheckConfig("unloze_tracerpref")) 
	{
		db = SQL_Connect("unloze_tracerpref", true, error, sizeof(error));
	}
	if (db == null)
	{
		CPrintToChatAll("{green}[Unloze] {white}Error! Could not connect to MYSQL-DB!");
		delete db;
		return;
	}
	//create tables
	char sQuery[255];
	char sSID[64];
	GetClientAuthId(client, AuthId_Steam2, sSID, sizeof(sSID));
	if (g_iTracerpref[client] == 1)
	{
		Format(sQuery, sizeof(sQuery), "INSERT INTO `unloze_tracerpref` (`steam_id`, `disabled`) VALUES ('%s','1') ON DUPLICATE KEY UPDATE `disabled` = '1'", sSID);
	}
	else if (g_iTracerpref[client] == 0)
	{
		Format(sQuery, sizeof(sQuery), "DELETE FROM unloze_tracerpref WHERE `steam_id` = '%s'", sSID);
	}
	SQL_TQuery(db, DummyCallbackSimple, sQuery);
	
	delete db;
}


public void CheckMYSQLTracerColorPref(int client)
{
	char error[255];
	Database db; 
	//the points not related to hlstats are stored together with tracer prefferences but have
	//their own table
	if (SQL_CheckConfig("unloze_tracerpref"))
	{
		db = SQL_Connect("unloze_tracerpref", true, error, sizeof(error));
	}
	if (db == null)
	{
		PrintToChat(client, "{green}[Unloze] {white}Error! Could not connect to MYSQL-DB!");
		delete db;
		return;
	}
	char sSID[64];
	GetClientAuthId(client, AuthId_Steam2, sSID, sizeof(sSID));
	char sQuery[512];
	Format(sQuery, sizeof(sQuery), "SELECT Color FROM `unloze_tracerprefColor` WHERE `steam_id` = '%s'", sSID);
	DBResultSet rs;
	
	if ((rs = SQL_Query(db, sQuery)) == null)
	{	
		delete db;
		delete rs;
		return;
	}
	if (rs.RowCount > 0 && rs.FetchRow())
	{
		char translate[124];
		char sPart[3][526];
		SQL_FetchString(rs, 0, translate, MAX_NAME_LENGTH);
		ExplodeString(translate, " ", sPart, 3, 526);
		g_iStoreColors[client][0] = StringToInt(sPart[0]);
		g_iStoreColors[client][1] = StringToInt(sPart[1]);
		g_iStoreColors[client][2] = StringToInt(sPart[2]);
		g_bStoreColorbool[client] = true;
		delete rs;
		delete db;
		return;
	}
	g_iStoreColors[client][0] = 0;
	g_iStoreColors[client][1] = 0;
	g_iStoreColors[client][2] = 0;
	delete rs;
	delete db;
} 

public void tracerprefMYSQLpostadmin(int client)
{
	char error[255];
	Database db;
	if (SQL_CheckConfig("unloze_tracerpref")) 
	{
		db = SQL_Connect("unloze_tracerpref", true, error, sizeof(error));
	}
	if (db == null)
	{
		CPrintToChatAll("{green}[Unloze] {white}Error! Could not connect to MYSQL-DB!");
		delete db;
		return;
	}
	//create tables
	char sQuery[255];
	char sSID[64];
	GetClientAuthId(client, AuthId_Steam2, sSID, sizeof(sSID));
	Format(sQuery, sizeof(sQuery), "SELECT disabled FROM `unloze_tracerpref` WHERE `steam_id` = '%s'", sSID);
	
	DBResultSet rs;
	if ((rs = SQL_Query(db, sQuery)) == null)
	{
		delete db;
		delete rs;
		return;
	}
	
	if (!(rs.RowCount > 0))
	{
		g_iTracerpref[client] = 0;
	}
	else
	{
		g_iTracerpref[client] = 1;
	}
	delete rs;
	delete db;
}

public void CheckFlagsMYSQL(int client)
{
	char error[255];
	Database db; 
	if (SQL_CheckConfig("unloze_tracerpref"))
	{
		db = SQL_Connect("unloze_tracerpref", true, error, sizeof(error));
	}
	if (db == null)
	{
		PrintToChat(client, "{green}[Unloze] {white}Error! Could not connect to MYSQL-DB!");
		delete db;
		return;
	}
	char sSID[64];
	GetClientAuthId(client, AuthId_Steam2, sSID, sizeof(sSID));
	char sQuery[512];
	Format(sQuery, sizeof(sQuery), "SELECT storestats FROM `unloze_zonepoints` WHERE `steam_id` = '%s'", sSID);
	
	DBResultSet rs;
	
	if ((rs = SQL_Query(db, sQuery)) == null)
	{	
		delete db;
		delete rs;
		return;
	}
	
	if (rs.FetchRow())
	{
		SQL_FetchString(rs, 0, g_cStorestats[client], sizeof(g_cStorestats));
	}
	delete rs;
	delete db;
} 

//----------------------------------------------------------------------------------------------------
// Purpose: stocks
//----------------------------------------------------------------------------------------------------

public void DummyCallbackSimple(Handle hOwner, Handle hChild, const char[] err, DataPack pack1)
{
	if (hOwner == null || hChild == null)
	{
		LogError("Query error. (%s)", err);
	}
}

stock bool IsValidClient(int client)
{
	if (client > 0 && client <= MaxClients && IsClientConnected(client) && IsClientInGame(client) && !IsFakeClient(client))
	{
		return true;
	}
	return false;
}

stock void ClientCount()
{
	g_iPlayerCount = 0;
	g_iPlayerCountTop10 = 0;
	for (int i = 1; i <= MaxClients; i++)
	{
		if (IsValidClient(i) && g_iTracerpref[i] == 0)
		{
			if (g_iPlayerRank[i] < 4 || g_bZeusOwner[i])
			{
				g_iPlayerArrayTop10[g_iPlayerCountTop10++] = i;
			}
			g_iPlayerArray[g_iPlayerCount++] = i;
		}
	}
}

stock bool colorIndex(int colors[3], int a, int g, int b)
{
	if (colors[0] == a && colors[1] == g && colors[2] == b)
	{
		return true;
	}
	return false;
}