#include "inc_debug"
#include "s_mmm_inc"

void main()
{
    object oPortal = OBJECT_SELF;
    object oUser = GetLastUsedBy();

    // Retrieve tent and area references
    object oTent = GetLocalObject(oPortal, "CAS_CTF_TENT_OBJECT");
    object oCTFArea = GetLocalObject(oPortal, "CAS_CTF_AREA");
    
    SendMessageToPC(oUser, "hi.");

    if (!GetIsObjectValid(oTent) || !GetIsObjectValid(oCTFArea))
    {
        SendMessageToPC(oUser, "Error: Tent or area reference is invalid.");
        return;
    }

    // Retrieve tent's original location
    location lExitLocation = GetLocalLocation(oTent, "CAS_CTF_EXIT_LOC");
    object oArea = GetAreaFromLocation(lExitLocation);
    vector vPosition = GetPositionFromLocation(lExitLocation);

    // Manually verify the validity of the location
    if (GetIsObjectValid(oArea) && (vPosition.x != 0.0 || vPosition.y != 0.0 || vPosition.z != 0.0))
    {
        // Teleport the player back to the tent's original location
        AssignCommand(oUser, JumpToLocation(lExitLocation));
        SendMessageToPC(oUser, "You have exited the CTF Tent.");
    }
    else
    {
        SendMessageToPC(oUser, "Error: Tent exit location is invalid.");
        return;
    }

    // Check for remaining players in the tent area
    object oPlayer = GetFirstObjectInArea(oCTFArea);
    while (GetIsObjectValid(oPlayer))
    {
        if (GetIsPC(oPlayer)) // Found a PC still in the area
        {
            SendMessageToPC(oUser, "Other players are still inside the tent. The area will remain active.");
            return; // Stop the script, do not destroy the area
        }
        oPlayer = GetNextObjectInArea(oCTFArea);
    }

    // No players left in the area, destroy it
    DestroyArea(oCTFArea);
    SendMessageToPC(oUser, "All players have left the tent. The CTF Tent area has been destroyed.");
}
