<?php require_once __DIR__ . '/includes/admin_bootstrap.php';
$messages = ugfx_chat_messages(0);
$schedules = ugfx_read_json($ugfx['storage']['chat_schedule'], []);
$bannedWords = ugfx_read_json($ugfx['storage']['banned_words'], []);
$notice = '';
$editingSchedule = null;
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);
        $notice = 'Chat message removed.';
    } elseif ($action === 'clear_chat') {
        ugfx_write_json($ugfx['storage']['chat'], []);
        $messages = [];
        $notice = 'Chat cleared.';
    } 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('/
|
|
/', (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('/
|
|
/', (string)($_POST['banned_words'] ?? '')))));
        ugfx_write_json($ugfx['storage']['banned_words'], $words);
        $bannedWords = $words;
        $notice = 'Blocked words 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="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">LATEST</div><div class="text-secondary small"><?= htmlspecialchars((string)(($messages ? end($messages)['created_at'] : 'No messages yet'))) ?></div></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">LIVE PROMOS</div><h3>Scheduled messages</h3><div class="ugfx-admin-list"><?php foreach ($schedules as $item): ?><div class="ugfx-admin-item"><h5><?= htmlspecialchars((string)($item['title'] ?? 'Promo')) ?></h5><div class="ugfx-admin-meta"><span>Every <?= (int)($item['interval_minutes'] ?? 60) ?> min</span><span><?= !empty($item['enabled']) ? 'Enabled' : 'Disabled' ?></span></div><div class="mt-2 text-secondary"><?= htmlspecialchars((string)($item['message'] ?? '')) ?></div><div class="ugfx-admin-actions"><a class="btn ugfx-btn-outline btn-sm" href="chat.php?edit_schedule=<?= urlencode((string)($item['id'] ?? '')) ?>">Edit</a><form method="post" onsubmit="return confirm('Delete this promo schedule?');"><input type="hidden" name="action" value="delete_schedule"><input type="hidden" name="id" value="<?= htmlspecialchars((string)($item['id'] ?? '')) ?>"><button class="btn btn-outline-danger btn-sm">Delete</button></form></div></div><?php endforeach; ?><?php if (!$schedules): ?><div class="ugfx-admin-empty">No promo schedules yet.</div><?php endif; ?></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><span class="ugfx-chip"><?= count($messages) ?> messages</span></div><div class="ugfx-admin-list"><?php foreach (array_reverse(array_slice($messages, -120)) as $msg): ?><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></div><?php if (!empty($msg['message'])): ?><div class="mt-2"><?= ugfx_safe_links((string)$msg['message']) ?></div><?php endif; ?><?php if (!empty($msg['sticker'])): ?><div class="mt-2">Sticker: <?= htmlspecialchars((string)$msg['sticker']) ?></div><?php endif; ?><?php if (!empty($msg['gif_url'])): ?><div class="mt-2"><img src="<?= htmlspecialchars((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><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>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>