<?php require_once __DIR__ . '/includes/admin_bootstrap.php';
ugfx_require_permission('chat');
$messages = ugfx_chat_messages(0);
$schedules = ugfx_read_json($ugfx['storage']['chat_schedule'], []);
$bannedWords = ugfx_read_json($ugfx['storage']['banned_words'], []);
$chatBanData = ugfx_chat_ban_data();
$settings = ugfx_get_settings();
$chatStatus = ugfx_chat_public_status();
$notice = '';
$editingSchedule = null;
$currentAdminUser = ugfx_admin_current_user();
$djList = array_values(array_filter(ugfx_read_json($ugfx['storage']['djs'], []), fn($item) => is_array($item) && (!isset($item['visible']) || !empty($item['visible']))));
usort($djList, fn($a, $b) => (int)($a['sort_order'] ?? 999) <=> (int)($b['sort_order'] ?? 999));
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    if ($action === 'delete_message') {
        $id = (string)($_POST['id'] ?? '');
        $messages = array_values(array_filter($messages, fn($item) => (string)($item['id'] ?? '') !== $id));
        ugfx_write_json($ugfx['storage']['chat'], $messages);
        ugfx_admin_log('chat_message_deleted', ['id' => $id]);
        $notice = 'Chat message removed.';
    } elseif ($action === 'clear_chat') {
        ugfx_write_json($ugfx['storage']['chat'], []);
        $messages = [];
        ugfx_admin_log('chat_cleared');
        $notice = 'Chat cleared.';
    } elseif ($action === 'save_chat_settings') {
        $settings = ugfx_get_settings();
        $settings['chat_enabled'] = isset($_POST['chat_enabled']);
        $settings['chat_disabled_message'] = trim((string)($_POST['chat_disabled_message'] ?? '')) ?: 'Chat is currently turned off by the station team. Please check back later.';
        ugfx_save_settings($settings);
        ugfx_admin_log('chat_settings_saved', ['enabled' => !empty($settings['chat_enabled'])]);
        $settings = ugfx_get_settings();
        $chatStatus = ugfx_chat_public_status();
        $notice = 'Chat switch updated.';
    } elseif ($action === 'system_post') {
        $text = trim((string)($_POST['system_message'] ?? ''));
        if ($text !== '') { ugfx_chat_add(['name' => 'System', 'message' => $text, 'type' => 'system']); $notice = 'System message posted.'; }
        $messages = ugfx_chat_messages(0);
    } elseif ($action === 'save_schedule') {
        $id = trim((string)($_POST['id'] ?? '')) ?: (string)(time() . random_int(100,999));
        $entry = [
            'id' => $id,
            'title' => trim((string)($_POST['title'] ?? '')),
            'message' => trim((string)($_POST['message'] ?? '')),
            'links' => array_values(array_filter(array_map('trim', preg_split('/\r\n|\r|\n/', (string)($_POST['links'] ?? ''))))),
            'interval_minutes' => max(5, (int)($_POST['interval_minutes'] ?? 60)),
            'enabled' => isset($_POST['enabled']),
            'last_sent' => trim((string)($_POST['last_sent'] ?? '')) ?: null,
        ];
        $updated = false;
        foreach ($schedules as &$item) { if ((string)($item['id'] ?? '') === $id) { $item = $entry; $updated = true; break; } }
        unset($item);
        if (!$updated) $schedules[] = $entry;
        ugfx_write_json($ugfx['storage']['chat_schedule'], array_values($schedules));
        $notice = $updated ? 'Promo schedule updated.' : 'Promo schedule created.';
        $schedules = ugfx_read_json($ugfx['storage']['chat_schedule'], []);
    } elseif ($action === 'delete_schedule') {
        $id = (string)($_POST['id'] ?? '');
        $schedules = array_values(array_filter($schedules, fn($item) => (string)($item['id'] ?? '') !== $id));
        ugfx_write_json($ugfx['storage']['chat_schedule'], $schedules);
        $notice = 'Promo schedule deleted.';
    } elseif ($action === 'save_banned_words') {
        $words = array_values(array_filter(array_map('trim', preg_split('/\r\n|\r|\n/', (string)($_POST['banned_words'] ?? '')))));
        ugfx_write_json($ugfx['storage']['banned_words'], $words);
        ugfx_admin_log('chat_banned_words_saved', ['count' => count($words)]);
        $bannedWords = $words;
        $notice = 'Blocked words updated.';
    } elseif (in_array($action, ['ban_name','mute_name','unban_name','unmute_name'], true)) {
        $name = trim((string)($_POST['chat_name'] ?? ''));
        if ($name !== '') {
            if ($action === 'ban_name' && !in_array($name, $chatBanData['banned'], true)) $chatBanData['banned'][] = $name;
            if ($action === 'mute_name' && !in_array($name, $chatBanData['muted'], true)) $chatBanData['muted'][] = $name;
            if ($action === 'unban_name') $chatBanData['banned'] = array_values(array_filter($chatBanData['banned'], fn($item) => strcasecmp($item, $name) !== 0));
            if ($action === 'unmute_name') $chatBanData['muted'] = array_values(array_filter($chatBanData['muted'], fn($item) => strcasecmp($item, $name) !== 0));
            ugfx_save_chat_ban_data($chatBanData);
            $chatBanData = ugfx_chat_ban_data();
            $notice = 'Chat name controls updated.';
        }
    }
}
$editScheduleId = (string)($_GET['edit_schedule'] ?? '');
foreach ($schedules as $item) { if ((string)($item['id'] ?? '') === $editScheduleId) { $editingSchedule = $item; break; } }
$adminTitle='Chat Tools'; include __DIR__ . '/includes/admin_header.php'; ?>
<?php if ($notice): ?><div class="ugfx-admin-alert"><?= htmlspecialchars($notice) ?></div><?php endif; ?>
<div class="ugfx-card p-4 mb-4">
  <div class="ugfx-admin-toolbar mb-3">
    <div><div class="ugfx-micro-label">CHAT MASTER SWITCH</div><h3 class="mb-0">Turn public chat on or off</h3></div>
    <span class="ugfx-chip <?= $chatStatus['enabled'] ? 'ugfx-chip-blue' : '' ?>"><?= $chatStatus['enabled'] ? 'Public chat live' : 'Public chat off' ?></span>
  </div>
  <form method="post" class="row g-3 align-items-start">
    <input type="hidden" name="action" value="save_chat_settings">
    <div class="col-lg-3">
      <div class="form-check form-switch mt-2">
        <input class="form-check-input" type="checkbox" role="switch" id="chatEnabledSwitch" name="chat_enabled" <?= $chatStatus['enabled'] ? 'checked' : '' ?>>
        <label class="form-check-label" for="chatEnabledSwitch">Enable public chat</label>
      </div>
    </div>
    <div class="col-lg-7">
      <label class="form-label">Offline message shown on public chat page</label>
      <textarea class="form-control" name="chat_disabled_message" rows="2" placeholder="Chat is currently turned off by the station team. Please check back later."><?= htmlspecialchars((string)($settings['chat_disabled_message'] ?? 'Chat is currently turned off by the station team. Please check back later.')) ?></textarea>
    </div>
    <div class="col-lg-2 d-grid">
      <label class="form-label d-none d-lg-block">&nbsp;</label>
      <button class="btn ugfx-btn-primary">Save chat switch</button>
    </div>
  </form>
</div>
<div class="ugfx-card p-4 mb-4">
  <div class="ugfx-admin-toolbar mb-3">
    <div><div class="ugfx-micro-label">ADMIN DJ CHAT</div><h3 class="mb-0">Live room inside admin</h3></div>
    <span class="ugfx-chip">Posting as <strong class="ms-1"><?= htmlspecialchars((string)($currentAdminUser['username'] ?? 'Admin')) ?></strong> / <?= htmlspecialchars(ucfirst((string)($currentAdminUser['role'] ?? 'admin'))) ?></span>
  </div>
  <div class="row g-4">
    <div class="col-xxl-2 col-xl-3">
      <div class="ugfx-card p-4 h-100">
        <div class="ugfx-micro-label">DJ QUICK SWITCH</div>
        <h4 class="mb-3">Jump in as the current DJ</h4>
        <p class="text-secondary">Pick a name below or type your own. The state badge will switch between admin and DJ mode live.</p>
        <div class="d-flex flex-wrap gap-2 mb-3">
          <button type="button" class="btn ugfx-btn-outline btn-sm" data-chat-name-preset="<?= htmlspecialchars((string)($currentAdminUser['username'] ?? 'Admin DJ')) ?>"><?= htmlspecialchars((string)($currentAdminUser['username'] ?? 'Admin DJ')) ?></button>
          <?php foreach (array_slice($djList, 0, 12) as $dj): $djName = trim((string)($dj['name'] ?? '')); if ($djName === '') continue; ?>
            <button type="button" class="btn ugfx-btn-outline btn-sm" data-chat-name-preset="<?= htmlspecialchars($djName) ?>"><?= htmlspecialchars($djName) ?></button>
          <?php endforeach; ?>
        </div>
        <div class="ugfx-admin-empty">Same optimized media system as public chat, now with search, filters, and lazy-loaded local radio-themed packs.</div>
      </div>
    </div>
    <div class="col-xxl-10 col-xl-9">
      <div class="ugfx-chat-shell ugfx-chat-shell-admin" id="ugfxChatApp" data-chat-get="../api/chat_get.php" data-chat-post="../api/chat_post.php" data-chat-upload="../api/chat_upload_audio.php" data-asset-prefix="../" data-media-manifest="../assets/chat-media/manifest.php" data-admin-name="<?= htmlspecialchars((string)($currentAdminUser['username'] ?? 'Admin')) ?>" data-admin-role="<?= htmlspecialchars((string)($currentAdminUser['role'] ?? 'admin')) ?>">
        <div class="ugfx-chat-main w-100">
          <div class="ugfx-card ugfx-chat-stage">
            <div class="ugfx-chat-topbar">
              <div>
                <div class="ugfx-micro-label">LIVE ROOM</div>
                <h3 class="mb-0">DJ interaction box</h3>
                <div class="mt-2"><span class="ugfx-chip" data-posting-badge>Posting as admin</span></div>
              </div>
              <div class="ugfx-chat-topstats"><span class="ugfx-chip"><i class="bi bi-chat-dots"></i> <span data-chat-count><?= count($messages) ?></span> messages</span><a class="btn ugfx-btn-outline btn-sm" href="../chat.php" target="_blank" rel="noopener"><i class="bi bi-box-arrow-up-right"></i> Open public chat</a></div>
            </div>
            <div class="ugfx-chat-feed" data-chat-feed></div>
            <div class="ugfx-chat-composer-wrap">
              <form class="ugfx-chat-composer" data-chat-form>
                <div class="ugfx-chat-name-row"><label class="form-label mb-1">Display name</label><input class="form-control" type="text" name="name" maxlength="30" placeholder="Current DJ name" value="<?= htmlspecialchars((string)($currentAdminUser['username'] ?? '')) ?>" required></div>
                <div class="ugfx-chat-editor"><textarea class="form-control" name="message" rows="3" maxlength="600" placeholder="Jump in with requests, shoutouts, station hype, or live DJ updates..."></textarea><input type="hidden" name="gif_url"><input type="hidden" name="sticker"><input type="hidden" name="voice_url"><input type="hidden" name="voice_mime">
                <input type="hidden" name="text_color" value="#f3f7ff"><div class="ugfx-chat-attachments" data-chat-attachments></div>
                <div class="ugfx-chat-color-row"><label class="small text-secondary">Your text color</label><input type="color" value="#66d9ff" data-text-color-picker aria-label="Choose chat text color"><span class="ugfx-chip ugfx-chip-blue small">Listeners can style their own messages</span></div><div class="ugfx-chat-toolbar"><button class="btn ugfx-btn-outline btn-sm" type="button" data-panel-toggle="emoji"><i class="bi bi-emoji-smile"></i> Emoji</button><button class="btn ugfx-btn-outline btn-sm" type="button" data-panel-toggle="stickers"><i class="bi bi-stars"></i> Stickers</button><button class="btn ugfx-btn-outline btn-sm" type="button" data-panel-toggle="gif"><i class="bi bi-images"></i> GIF</button><button class="btn ugfx-btn-outline btn-sm" type="button" data-record-toggle><i class="bi bi-mic"></i> Voice</button><a class="btn ugfx-btn-outline btn-sm" href="../listen-live.php" target="_blank" rel="noopener"><i class="bi bi-play-circle"></i> Main Player</a><a class="btn ugfx-btn-outline btn-sm" href="../player-popup.php" target="_blank" rel="noopener"><i class="bi bi-window"></i> Popup Player</a><button class="btn ugfx-btn-primary ms-auto" type="submit"><i class="bi bi-send-fill"></i> Send live</button></div></div>
                <div class="ugfx-chat-panels"><section class="ugfx-chat-panel" data-panel="emoji" hidden><div class="ugfx-chat-panel-head"><strong>Emoji blast</strong><input class="form-control form-control-sm" type="search" placeholder="Search emoji" data-emoji-search></div><div class="ugfx-chat-chip-row"><button type="button" class="ugfx-mini-chip active" data-emoji-filter="all">All</button><button type="button" class="ugfx-mini-chip" data-emoji-filter="faces">Faces</button><button type="button" class="ugfx-mini-chip" data-emoji-filter="energy">Energy</button><button type="button" class="ugfx-mini-chip" data-emoji-filter="music">Music</button><button type="button" class="ugfx-mini-chip" data-emoji-filter="love">Love</button><button type="button" class="ugfx-mini-chip" data-emoji-filter="party">Party</button></div><div class="ugfx-emoji-grid" data-emoji-grid></div></section><section class="ugfx-chat-panel" data-panel="stickers" hidden><div class="ugfx-chat-panel-head"><strong>Sticker drops</strong><span class="text-secondary small">Local radio pack · showing <span data-sticker-count>0/0</span></span></div><input class="form-control form-control-sm" type="search" placeholder="Search stickers: live, dj, party, request..." data-sticker-search><div class="ugfx-chat-chip-row mt-2" data-sticker-filters></div><div class="ugfx-sticker-grid" data-sticker-grid></div><div class="ugfx-chat-panel-actions"><button type="button" class="btn ugfx-btn-outline btn-sm" data-sticker-load-more hidden>Load more stickers</button></div></section><section class="ugfx-chat-panel" data-panel="gif" hidden><div class="ugfx-chat-panel-head"><strong>GIF launcher</strong><span class="text-secondary small">Local themed pack · showing <span data-gif-count>0/0</span></span></div><div class="row g-2 align-items-center"><div class="col-md-8"><input type="url" class="form-control" placeholder="https://...gif or any direct GIF" data-gif-url-input></div><div class="col-md-4 d-grid"><button type="button" class="btn ugfx-btn-outline" data-gif-attach><i class="bi bi-plus-circle"></i> Attach GIF</button></div></div><input class="form-control form-control-sm mt-2" type="search" placeholder="Search GIFs: radio, dance, party, night..." data-gif-search><div class="ugfx-chat-chip-row mt-2" data-gif-filters></div><div class="ugfx-gif-grid" data-gif-presets></div><div class="ugfx-chat-panel-actions"><button type="button" class="btn ugfx-btn-outline btn-sm" data-gif-load-more hidden>Load more GIFs</button></div></section></div>
                <div class="ugfx-chat-status-row"><div class="text-secondary small" data-chat-status>Admin DJ chat ready.</div><div class="text-secondary small" data-record-status></div></div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<div class="row g-4 mb-4"><div class="col-md-3"><div class="ugfx-card p-4"><div class="ugfx-micro-label">MESSAGES</div><h2><?= count($messages) ?></h2></div></div><div class="col-md-3"><div class="ugfx-card p-4"><div class="ugfx-micro-label">PROMOS</div><h2><?= count($schedules) ?></h2></div></div><div class="col-md-3"><div class="ugfx-card p-4"><div class="ugfx-micro-label">BLOCKED WORDS</div><h2><?= count($bannedWords) ?></h2></div></div><div class="col-md-3"><div class="ugfx-card p-4"><div class="ugfx-micro-label">NAME LOCKS</div><h2><?= count($chatBanData['banned']) + count($chatBanData['muted']) ?></h2></div></div></div>
<div class="ugfx-admin-grid mb-4"><div class="ugfx-card p-4"><div class="ugfx-micro-label">SYSTEM TOOLS</div><h3>Post and moderate</h3><form method="post" class="ugfx-admin-form row g-3 mb-4"><input type="hidden" name="action" value="system_post"><div class="col-12"><textarea class="form-control" name="system_message" rows="5" placeholder="Post a system message into chat"></textarea></div><div class="col-12"><button class="btn ugfx-btn-primary">Post system message</button></div></form><form method="post" onsubmit="return confirm('Clear the full chat feed?');"><input type="hidden" name="action" value="clear_chat"><button class="btn btn-outline-danger">Clear entire chat</button></form></div><div class="ugfx-card p-4"><div class="ugfx-micro-label">BLOCKED WORDS</div><h3>Spam filter words</h3><form method="post" class="ugfx-admin-form row g-3"><input type="hidden" name="action" value="save_banned_words"><div class="col-12"><textarea class="form-control" name="banned_words" rows="10" placeholder="One word or phrase per line"><?= htmlspecialchars(implode(PHP_EOL, $bannedWords)) ?></textarea></div><div class="col-12"><button class="btn ugfx-btn-primary">Save blocked words</button></div></form></div></div>
<div class="ugfx-admin-grid mb-4"><div class="ugfx-card p-4"><div class="ugfx-micro-label">PROMO SCHEDULER</div><h3><?= $editingSchedule ? 'Edit promo' : 'Create promo' ?></h3><form method="post" class="ugfx-admin-form row g-3"><input type="hidden" name="action" value="save_schedule"><input type="hidden" name="id" value="<?= htmlspecialchars((string)($editingSchedule['id'] ?? '')) ?>"><div class="col-12"><input class="form-control" name="title" placeholder="Title" value="<?= htmlspecialchars((string)($editingSchedule['title'] ?? '')) ?>"></div><div class="col-12"><textarea class="form-control" name="message" rows="5" placeholder="Promo message"><?= htmlspecialchars((string)($editingSchedule['message'] ?? '')) ?></textarea></div><div class="col-12"><textarea class="form-control" name="links" rows="4" placeholder="One link per line"><?= htmlspecialchars(implode(PHP_EOL, (array)($editingSchedule['links'] ?? []))) ?></textarea></div><div class="col-md-6"><input class="form-control" type="number" name="interval_minutes" min="5" value="<?= (int)($editingSchedule['interval_minutes'] ?? 60) ?>"></div><div class="col-md-6 d-flex align-items-center"><div class="form-check"><input class="form-check-input" type="checkbox" name="enabled" id="promoEnabled" <?= !isset($editingSchedule['enabled']) || !empty($editingSchedule['enabled']) ? 'checked' : '' ?>><label class="form-check-label" for="promoEnabled">Enabled</label></div></div><div class="col-12 d-flex gap-2 flex-wrap"><button class="btn ugfx-btn-primary">Save promo schedule</button><?php if ($editingSchedule): ?><a class="btn ugfx-btn-outline" href="chat.php">New promo</a><?php endif; ?></div></form></div><div class="ugfx-card p-4"><div class="ugfx-micro-label">NAME BANS & MUTES</div><h3>Direct chat control</h3><div class="row g-3"><div class="col-md-6"><div class="ugfx-admin-empty mb-2">Banned usernames</div><?php foreach ($chatBanData['banned'] as $name): ?><form method="post" class="d-flex gap-2 mb-2"><input type="hidden" name="action" value="unban_name"><input type="hidden" name="chat_name" value="<?= htmlspecialchars($name) ?>"><span class="ugfx-chip flex-grow-1"><?= htmlspecialchars($name) ?></span><button class="btn btn-outline-danger btn-sm">Unban</button></form><?php endforeach; if (!$chatBanData['banned']): ?><div class="text-secondary small">No banned usernames.</div><?php endif; ?></div><div class="col-md-6"><div class="ugfx-admin-empty mb-2">Muted usernames</div><?php foreach ($chatBanData['muted'] as $name): ?><form method="post" class="d-flex gap-2 mb-2"><input type="hidden" name="action" value="unmute_name"><input type="hidden" name="chat_name" value="<?= htmlspecialchars($name) ?>"><span class="ugfx-chip flex-grow-1"><?= htmlspecialchars($name) ?></span><button class="btn btn-outline-warning btn-sm">Unmute</button></form><?php endforeach; if (!$chatBanData['muted']): ?><div class="text-secondary small">No muted usernames.</div><?php endif; ?></div></div></div></div>
<div class="ugfx-card p-4"><div class="ugfx-admin-toolbar"><div><div class="ugfx-micro-label">CHAT FEED</div><h3 class="mb-0">Moderate chat messages</h3></div><div class="d-flex gap-2 flex-wrap"><span class="ugfx-chip"><span data-admin-moderation-count><?= count($messages) ?></span> messages</span><form method="post" onsubmit="return confirm('Clear the full chat feed?');"><input type="hidden" name="action" value="clear_chat"><button class="btn btn-outline-danger btn-sm">Clear all</button></form></div></div><div class="ugfx-admin-empty mb-3"><strong>Quick moderation box</strong><div class="small mt-2">Type any chat name here to ban or mute it fast without hunting through the feed.</div><form method="post" class="row g-2 mt-2"><div class="col-md-6"><input class="form-control" type="text" name="chat_name" placeholder="Username to moderate"></div><div class="col-md-6 d-flex gap-2"><button class="btn btn-outline-danger btn-sm" name="action" value="ban_name">Ban username</button><button class="btn btn-outline-warning btn-sm" name="action" value="mute_name">Mute username</button></div></form></div><div class="small text-secondary mb-3">This moderation list now refreshes automatically so new posts show up without reloading the page.</div><div class="ugfx-admin-list" data-admin-moderation-list><?php foreach (array_reverse(array_slice($messages, -120)) as $msg): $state = ugfx_chat_name_state((string)($msg['name'] ?? '')); ?><div class="ugfx-admin-item"><div class="ugfx-chat-admin-row"><div><div class="ugfx-admin-meta"><span><?= htmlspecialchars((string)($msg['name'] ?? 'Guest')) ?></span><span><?= htmlspecialchars((string)($msg['created_at'] ?? '')) ?></span><span><?= htmlspecialchars((string)($msg['type'] ?? 'user')) ?></span><?php if ($state !== 'ok'): ?><span><?= htmlspecialchars(strtoupper($state)) ?></span><?php endif; ?></div><?php if (!empty($msg['message'])): ?><div class="mt-2" style="color: <?= htmlspecialchars((string)($msg['text_color'] ?? '#f3f7ff')) ?>;"><?= ugfx_safe_links((string)$msg['message']) ?></div><?php endif; ?><?php if (!empty($msg['sticker'])): ?><?php $sticker = (string)$msg['sticker']; ?><?php if (preg_match('/\.(png|jpe?g|gif|webp|svg)$/i', $sticker)): ?><div class="mt-2"><img src="<?= htmlspecialchars((preg_match('#^(?:https?:)?//#i', $sticker) || str_starts_with($sticker, '/')) ? $sticker : '../' . ltrim($sticker, '/')) ?>" alt="Sticker" style="max-width:180px;border-radius:14px;"></div><?php else: ?><div class="mt-2">Sticker: <?= htmlspecialchars($sticker) ?></div><?php endif; ?><?php endif; ?><?php if (!empty($msg['gif_url'])): ?><div class="mt-2"><img src="<?= htmlspecialchars((preg_match('#^(?:https?:)?//#i', (string)$msg['gif_url']) || str_starts_with((string)$msg['gif_url'], '/')) ? (string)$msg['gif_url'] : '../' . ltrim((string)$msg['gif_url'], '/')) ?>" alt="GIF" style="max-width:240px;border-radius:14px;"></div><?php endif; ?><?php if (!empty($msg['voice_url'])): ?><div class="mt-2"><audio controls preload="none" src="../<?= htmlspecialchars(ltrim((string)$msg['voice_url'], '/')) ?>"></audio></div><?php endif; ?></div><div class="d-grid gap-2"><form method="post"><input type="hidden" name="action" value="ban_name"><input type="hidden" name="chat_name" value="<?= htmlspecialchars((string)($msg['name'] ?? '')) ?>"><button class="btn btn-outline-danger btn-sm">Ban name</button></form><form method="post"><input type="hidden" name="action" value="mute_name"><input type="hidden" name="chat_name" value="<?= htmlspecialchars((string)($msg['name'] ?? '')) ?>"><button class="btn btn-outline-warning btn-sm">Mute name</button></form><form method="post" onsubmit="return confirm('Remove this chat message?');"><input type="hidden" name="action" value="delete_message"><input type="hidden" name="id" value="<?= htmlspecialchars((string)($msg['id'] ?? '')) ?>"><button class="btn btn-outline-danger btn-sm">Delete</button></form></div></div></div><?php endforeach; ?><?php if (!$messages): ?><div class="ugfx-admin-empty">Chat is currently empty.</div><?php endif; ?></div></div>
<script>
window.UGFX_CHAT_BOOT = {
  initialMessages: <?= json_encode($messages, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ?>,
  adminName: <?= json_encode((string)($currentAdminUser['username'] ?? 'Admin')) ?>,
  adminRole: <?= json_encode((string)($currentAdminUser['role'] ?? 'admin')) ?>
};
document.addEventListener('click', function (event) {
  const btn = event.target.closest('[data-chat-name-preset]');
  if (!btn) return;
  const input = document.querySelector('#ugfxChatApp [name="name"]');
  if (!input) return;
  input.value = btn.getAttribute('data-chat-name-preset') || '';
  input.dispatchEvent(new Event('input', { bubbles: true }));
  input.focus();
});

(function () {
  const listEl = document.querySelector('[data-admin-moderation-list]');
  const countEl = document.querySelector('[data-admin-moderation-count]');
  if (!listEl) return;
  const apiUrl = '../api/chat_get.php';
  const esc = (value) => String(value ?? '').replace(/[&<>"']/g, function (ch) {
    return ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'})[ch] || ch;
  });
  const withLinks = (value) => esc(value).replace(/((https?:\/\/|www\.)[^\s<]+)/gi, function (url) {
    const href = /^https?:\/\//i.test(url) ? url : 'https://' + url;
    return '<a href="' + esc(href) + '" target="_blank" rel="noopener">' + esc(url) + '</a>';
  }).replace(/\n/g, '<br>');
  const mediaSrc = (value) => {
    const raw = String(value || '').trim();
    if (!raw) return '';
    if (/^(?:https?:)?\/\//i.test(raw) || raw.startsWith('/')) return raw;
    return '../' + raw.replace(/^\/+/, '');
  };
  const isImage = (value) => /\.(png|jpe?g|gif|webp|svg)$/i.test(String(value || ''));
  function renderModeration(messages) {
    const items = Array.isArray(messages) ? messages.slice(-120).reverse() : [];
    if (countEl) countEl.textContent = String(Array.isArray(messages) ? messages.length : 0);
    if (!items.length) {
      listEl.innerHTML = '<div class="ugfx-admin-empty">Chat is currently empty.</div>';
      return;
    }
    listEl.innerHTML = items.map((msg) => {
      const name = esc(msg.name || 'Guest');
      const created = esc(msg.created_at || '');
      const type = esc(msg.type || 'user');
      const textColor = esc(msg.text_color || '#f3f7ff');
      const messageHtml = msg.message ? '<div class="mt-2" style="color: ' + textColor + ';">' + withLinks(msg.message) + '</div>' : '';
      const stickerHtml = msg.sticker ? (isImage(msg.sticker)
        ? '<div class="mt-2"><img src="' + esc(mediaSrc(msg.sticker)) + '" alt="Sticker" style="max-width:180px;border-radius:14px;"></div>'
        : '<div class="mt-2">Sticker: ' + esc(msg.sticker) + '</div>') : '';
      const gifHtml = msg.gif_url ? '<div class="mt-2"><img src="' + esc(mediaSrc(msg.gif_url)) + '" alt="GIF" style="max-width:240px;border-radius:14px;"></div>' : '';
      const voiceHtml = msg.voice_url ? '<div class="mt-2"><audio controls preload="none" src="' + esc(mediaSrc(msg.voice_url)) + '"></audio></div>' : '';
      const rawName = esc(msg.name || '');
      const rawId = esc(msg.id || '');
      return '<div class="ugfx-admin-item"><div class="ugfx-chat-admin-row"><div><div class="ugfx-admin-meta"><span>' + name + '</span><span>' + created + '</span><span>' + type + '</span></div>' + messageHtml + stickerHtml + gifHtml + voiceHtml + '</div><div class="d-grid gap-2">'
        + '<form method="post"><input type="hidden" name="action" value="ban_name"><input type="hidden" name="chat_name" value="' + rawName + '"><button class="btn btn-outline-danger btn-sm">Ban name</button></form>'
        + '<form method="post"><input type="hidden" name="action" value="mute_name"><input type="hidden" name="chat_name" value="' + rawName + '"><button class="btn btn-outline-warning btn-sm">Mute name</button></form>'
        + '<form method="post" onsubmit="return confirm(\'Remove this chat message?\');"><input type="hidden" name="action" value="delete_message"><input type="hidden" name="id" value="' + rawId + '"><button class="btn btn-outline-danger btn-sm">Delete</button></form>'
        + '</div></div></div>';
    }).join('');
  }
  async function refreshModeration() {
    try {
      const res = await fetch(apiUrl, { cache: 'no-store' });
      const data = await res.json();
      if (data && data.ok && Array.isArray(data.messages)) renderModeration(data.messages);
    } catch (err) {}
  }
  setInterval(refreshModeration, 2500);
  refreshModeration();
})();
</script>
<script src="../assets/js/chat-room.js"></script>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>
