#include "channel_include"
#include "cas_casinoinc"

// Forward declare if compiled separately.
void LogPotentialAbuse(object oPC, int nCost, int nTokens, int nTokensPurchased, int nTokensSpent, string sGameName);

const float COOLDOWN_SECONDS = 7200.0f; // 2 hours
const string LOC_COOLDOWN = "CAS_SEX_ANNOUNCE_COOLDOWN";

void main()
{
    object oUser = GetLastUsedBy();
    if (!GetIsObjectValid(oUser) || !GetIsPC(oUser)) return;

    // Who/what is being used
    SendMessageToPC(oUser, "[Announcer] Used placeable: " + GetTag(OBJECT_SELF) + " (" + GetName(OBJECT_SELF) + ")");

    // Cooldown check on the placeable itself
    if (GetLocalInt(OBJECT_SELF, LOC_COOLDOWN) == 1)
    {
        SendMessageToPC(oUser, "[Announcer] Cooldown active. Cancelled.");
        SendMessageToPC(oUser, "This announcer is cooling down. Try again later.");
        return;
    }
    SendMessageToPC(oUser, "[Announcer] Cooldown OK. Proceeding.");

    // Find the nearest LISTENER to the USER (not the placeable)
    object oListener = GetNearestObjectByTag("C_CAS_GLORYLISTEN", oUser, 1);
    if (!GetIsObjectValid(oListener))
    {
        SendMessageToPC(oUser, "[Announcer] No listener found near you (C_CAS_GLORYLISTEN).");
        return;
    }
    if (GetObjectType(oListener) != OBJECT_TYPE_CREATURE)
    {
        SendMessageToPC(oUser, "[Announcer] Found object with tag C_CAS_GLORYLISTEN, but it's not a creature.");
        return;
    }

    float fDist = GetDistanceBetween(oUser, oListener);
    SendMessageToPC(oUser, "[Announcer] Using listener: " + GetTag(oListener) + " (" + GetName(oListener) + "), Dist=" + FloatToString(fDist, 2));

    // Compose anonymous message (no sender name shown in-channel)
    string sMsg = "Someone has entered the gloryhole at the Casino of Coins.";
    SendMessageToPC(oUser, "[Announcer] Message len=" + IntToString(GetStringLength(sMsg)) + " | Channel=CHANNEL_CUSTOM_PUBLIC_SEX | bAddChatSource=FALSE (anonymous)");

    // Send anonymously via the listener (do NOT add chat source)
    BroadcasteMessageToCustomPublicChannel(
        oListener,
        sMsg,
        CHANNEL_CUSTOM_PUBLIC_SEX, // 0x00000008
        FALSE                      // anonymous to players
    );
    SendMessageToPC(oUser, "[Announcer] Broadcast attempted.");

    // Staff-only log of who used it
    LogPotentialAbuse(oUser, 0, 0, 0, 0, "ANNOUNCER_SEX_ANON");
    SendMessageToPC(oUser, "[Announcer] Usage logged (staff-only).");

    // Arm cooldown
    SetLocalInt(OBJECT_SELF, LOC_COOLDOWN, 1);
    DelayCommand(COOLDOWN_SECONDS, DeleteLocalInt(OBJECT_SELF, LOC_COOLDOWN));
    SendMessageToPC(oUser, "[Announcer] Cooldown armed for 7200s.");
}
