#pragma semicolon 1
#include <sourcemod>
#include <sdktools>

#define TRIGGER_MIN_X -8.0
#define TRIGGER_MAX_X 8.0
#define TRIGGER_MIN_Y -8.0
#define TRIGGER_MAX_Y 8.0
#define TRIGGER_MIN_Z -500.0
#define TRIGGER_MAX_Z 500.0
#define SECOND_TRIGGER_X 64.0
#define SECOND_TRIGGER_Y 64.0
#define SECOND_TRIGGER_Z 110.0
#define SECOND_TRIGGER_MIN_X (SECOND_TRIGGER_X - 16.0)
#define SECOND_TRIGGER_MAX_X (SECOND_TRIGGER_X + 16.0)
#define SECOND_TRIGGER_MIN_Y (SECOND_TRIGGER_Y - 16.0)
#define SECOND_TRIGGER_MAX_Y (SECOND_TRIGGER_Y + 16.0)
#define SECOND_TRIGGER_MIN_Z (SECOND_TRIGGER_Z - 100.0)
#define SECOND_TRIGGER_MAX_Z (SECOND_TRIGGER_Z + 100.0)

bool IsInsideTrigger(float position[3])
{
    return (position[0] >= TRIGGER_MIN_X && position[0] <= TRIGGER_MAX_X &&
            position[1] >= TRIGGER_MIN_Y && position[1] <= TRIGGER_MAX_Y &&
            position[2] >= TRIGGER_MIN_Z && position[2] <= TRIGGER_MAX_Z);
}

bool IsInsideSecondTrigger(float position[3])
{
    return (position[0] >= SECOND_TRIGGER_MIN_X && position[0] <= SECOND_TRIGGER_MAX_X &&
            position[1] >= SECOND_TRIGGER_MIN_Y && position[1] <= SECOND_TRIGGER_MAX_Y &&
            position[2] >= SECOND_TRIGGER_MIN_Z && position[2] <= SECOND_TRIGGER_MAX_Z);
}

bool GetRandomSpawn(int team, float spawnPos[3])
{
    float spawnAxis[][3] = {
        {100.0, 100.0, 50.0},
        {-200.0, -200.0, 30.0},
    };
    
    int index = team - 2;
    if (index >= 0 && index < sizeof(spawnAxis))
    {
        spawnPos[0] = spawnAxis[index][0];
        spawnPos[1] = spawnAxis[index][1];
        spawnPos[2] = spawnAxis[index][2];
        return true;
    }
    
    return false;
}


public OnGameFrame()
{
    for (int client = 1; client <= MaxClients; client++)
    {
        if (!IsClientInGame(client) || !IsPlayerAlive(client) || !IsFakeClient(client))
            continue;

        float position[3];
        GetClientAbsOrigin(client, position);
        
        if (IsInsideTrigger(position))
        {
            int team = GetClientTeam(client);
            float spawnPos[3];

            if (GetRandomSpawn(team, spawnPos))
            {
                // Debug log before teleportation
                PrintToServer("Bot %N teleported from (%.1f, %.1f, %.1f) to (%.1f, %.1f, %.1f)", 
                              client, position[0], position[1], position[2], 
                              spawnPos[0], spawnPos[1], spawnPos[2]);

                TeleportEntity(client, spawnPos, NULL_VECTOR, NULL_VECTOR);
            }
        }
        if (IsInsideSecondTrigger(position))
{
    		int team = GetClientTeam(client);
    		float spawnPos[3];

    		if (GetRandomSpawn(team, spawnPos))
			{
        	PrintToServer("Bot %N redirected back to spawn from second trigger!", client);
        	TeleportEntity(client, spawnPos, NULL_VECTOR, NULL_VECTOR);
       		}
       	}        
    }
}
