#pragma semicolon 1
#define PLUGIN_AUTHOR "jenz"
#define PLUGIN_VERSION "1.0"
#include <sourcemod>
#include <cstrike>

Database g_hDatabase;
int g_ireward_days = 0;
char g_cadmin_sid[64];
char g_cadmin_escaped_name[256];

public Plugin myinfo =
{
    name = "unloze track event winners",
    author = PLUGIN_AUTHOR,
    description = "during events it tracks through the admin command if people won the event",
    version = PLUGIN_VERSION,
    url = "www.unloze.com"
};


public void OnPluginStart()
{
    if (!g_hDatabase)
    {
        Database.Connect(SQL_OnDatabaseConnect, "Event_notifier");
    }
    RegAdminCmd("sm_trackwinners", Cmd_trackwinners, ADMFLAG_GENERIC, "Use this each round where humans can win VIP. the alive humans on that round will have their steam IDs stored. Also specify a day as the number.");
    HookEvent("round_start", Event_RoundStart);
    HookEvent("round_end", Event_RoundEnd);
}

public void Event_RoundStart(Handle event, const char[] name, bool dontBroadcast)
{
    g_ireward_days = 0;
    Format(g_cadmin_sid, sizeof(g_cadmin_sid), "");
    Format(g_cadmin_escaped_name, sizeof(g_cadmin_escaped_name), "");
}

public void Event_RoundEnd(Handle event, const char[] name, bool dontBroadcast)
{
    int winner_team = GetEventInt(event, "winner");
    if (winner_team == 3 && g_ireward_days > 0) //ct won the round and are supposed to get vip for it.
    {
        char current_map[128];
        GetCurrentMap(current_map, sizeof(current_map));
        for (int i = 1; i <= MaxClients; i++)
        {
            //finally stopping STEAM_ID_STOP_IGNORING_RETVALS
            if (IsValidClient(i) && !IsFakeClient(i) && IsPlayerAlive(i) && GetClientTeam(i) == CS_TEAM_CT && IsClientAuthorized(i))
            {
                write_reward_entry(i, current_map);
            }
        }
    }
}

public void write_reward_entry(int client, char[] event_map)
{
    char sQuery[512];
    char sName[MAX_NAME_LENGTH];
    GetClientName(client, sName, sizeof(sName));
    int size2 = 2 * strlen(sName) + 1;
    char[] sEscapedName = new char[size2 + 1];
    g_hDatabase.Escape(sName, sEscapedName, size2 + 1);

    char SID[64];
    if (GetClientAuthId(client, AuthId_Steam2, SID, sizeof(SID)))
    {
        Format(sQuery, sizeof(sQuery), "INSERT INTO `rewards` (`steamid`, `username`, `event_map`, `event_reward_days`, `admin_created_reward_steamid`, `admin_created_reward_name`) VALUES ('%s', '%s', '%s', '%i', '%s', '%s')", SID, sEscapedName, event_map, g_ireward_days, g_cadmin_sid, g_cadmin_escaped_name);
        g_hDatabase.Query(DummyCallback, sQuery, DBPrio_Normal);
        PrintToChat(client, "Your %i days VIP were stored for winning this round. They will be awarded in the next 2-3 hours if you have a forum account.", g_ireward_days);
    }
    else
    {
        PrintToChat(client, "So sorry but your steam ID is not working. no vip for you.");
    }
}

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

public Action Cmd_trackwinners(int client, int args)
{
    if (!IsValidClient(client))
        return Plugin_Handled;
    if (args != 1)
    {
        ReplyToCommand(client, "[SM] sm_trackwinners <amount of days>");
        return Plugin_Handled;
    }
    char sDays[65];
    GetCmdArg(1, sDays, sizeof(sDays));
    g_ireward_days = StringToInt(sDays);

    GetClientAuthId(client, AuthId_Steam2, g_cadmin_sid, sizeof(g_cadmin_sid));

    char sName[MAX_NAME_LENGTH];
    GetClientName(client, sName, sizeof(sName));
    int size2 = 2 * strlen(sName) + 1;
    g_hDatabase.Escape(sName, g_cadmin_escaped_name, size2 + 1);

    PrintToChatAll("Admin %N set a VIP reward of %i days for winning this round", client, g_ireward_days);
    return Plugin_Handled;
}

public void SQL_OnDatabaseConnect(Database db, const char[] error, any data)
{
    if(!db || strlen(error))
    {
        LogError("Database error: %s", error);
        return;
    }
    g_hDatabase = db;
}

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