<?php
session_start();
require __DIR__ . '/auth.php';
$pageTitle = 'Live Chat — Admin';
require __DIR__ . '/includes/admin_header.php';

$settingsFile = __DIR__ . '/../data/settings.json';
$settings = [];
if (file_exists($settingsFile)) {
  $settings = json_decode(file_get_contents($settingsFile), true);
  if (!is_array($settings)) $settings = [];
}

function save_settings($file, $settings){
  file_put_contents($file, json_encode($settings, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
}

$chatFile = __DIR__ . '/../data/chat.json';
if (!file_exists($chatFile)) file_put_contents($chatFile, '[]');

$chatData = json_decode(file_get_contents($chatFile), true);
if (!is_array($chatData)) $chatData = [];
foreach ($chatData as $k => $row) {
  if (empty($row['id'])) {
    $chatData[$k]['id'] = 'chat_' . substr(md5(($row['ts'] ?? time()) . '|' . ($row['name'] ?? '') . '|' . ($row['msg'] ?? '')), 0, 12);
  }
}
file_put_contents($chatFile, json_encode($chatData, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (isset($_POST['save_chat_settings'])) {
    $settings['chat_enabled'] = !empty($_POST['chat_enabled']);
    $settings['chat_live_now'] = !empty($_POST['chat_live_now']);
    $settings['chat_show_in_nav'] = !empty($_POST['chat_show_in_nav']);
    $settings['chat_require_live'] = !empty($_POST['chat_require_live']);
    $auto = trim((string)($_POST['autodj_names'] ?? ''));
    $settings['autodj_names'] = array_values(array_filter(array_map('trim', explode(',', $auto))));

    save_settings($settingsFile, $settings);
    header('Location: chat.php?saved=1'); exit;
  }

  if (isset($_POST['clear_chat'])) {
    file_put_contents($chatFile, '[]');
    header('Location: chat.php?cleared=1'); exit;
  }

  if (isset($_POST['delete_msg'])) {
    $deleteId = trim((string)($_POST['delete_id'] ?? ''));
    $data = json_decode(file_get_contents($chatFile), true);
    if (!is_array($data)) $data = [];
    $data = array_values(array_filter($data, function($row) use ($deleteId){ return (string)($row['id'] ?? '') !== $deleteId; }));
    file_put_contents($chatFile, json_encode($data, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));
    header('Location: chat.php?deleted=1'); exit;
  }

  if (isset($_POST['admin_send'])) {
    $msg = trim((string)($_POST['msg'] ?? ''));
    $name = trim((string)($_POST['name'] ?? 'DJ'));
    if ($msg !== '') {
      $data = json_decode(file_get_contents($chatFile), true);
      if (!is_array($data)) $data = [];
      $data[] = ['id'=>'chat_' . substr(md5(uniqid('', true)),0,12),'role'=>'admin','name'=>$name,'msg'=>$msg,'time'=>date('H:i'),'ts'=>time()];
      if (count($data)>200) $data = array_slice($data, -200);
      file_put_contents($chatFile, json_encode($data, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));
    }
    header('Location: chat.php?sent=1'); exit;
  }
}

$chatEnabled = !empty($settings['chat_enabled']);
$chatLiveNow = !empty($settings['chat_live_now']);
$chatShowNav = array_key_exists('chat_show_in_nav', $settings) ? !empty($settings['chat_show_in_nav']) : true;

?>
<div class="admin-wrap">
  <a class="btn btn-accent" href="/admin/index.php">← Return to Admin</a>

  <div class="content-card">
    <h1 style="margin:0;">💬 Live Chat</h1>
    <div style="opacity:.85;">Enable/disable chat, show/hide the nav link, and post as admin.</div>
  </div>

  <?php if (!empty($_GET['saved'])): ?><div class="msg ok">Saved.</div><?php endif; ?>
  <?php if (!empty($_GET['cleared'])): ?><div class="msg ok">Chat cleared.</div><?php endif; ?>
  <?php if (!empty($_GET['sent'])): ?><div class="msg ok">Message sent.</div><?php endif; ?>
  <?php if (!empty($_GET['deleted'])): ?><div class="msg ok">Message deleted.</div><?php endif; ?>

  <div class="content-card" style="text-align:left;">
    <form method="post">
      <input type="hidden" name="save_chat_settings" value="1">
      <label style="display:block;margin:10px 0;">
        <input type="checkbox" name="chat_enabled" <?= $chatEnabled?'checked':''; ?>> Enable chat feature
      </label>
      <label style="display:block;margin:10px 0;">
        <input type="checkbox" name="chat_show_in_nav" <?= $chatShowNav?'checked':''; ?>> Show chat link in navigation (when live)
      </label>
      <label style="display:block;margin:10px 0;">
        <input type="checkbox" name="chat_live_now" <?= $chatLiveNow?'checked':''; ?>> Only show chat when Live DJ is on-air (based on Schedule)
      </label>

      <button class="btn btn-accent" type="submit">Save Settings</button>
    </form>
  </div>

  <div class="content-card chat-card" style="text-align:left;">
    <h2 style="margin-top:0;">Live Chat Feed</h2>
    <div id="adminChatBox" class="chat-box" aria-live="polite"></div>
    <div class="chat-hint">This updates automatically so you can reply in real time.</div>
  </div>


  <div class="content-card" style="text-align:left;">
    <h2 style="margin-top:0;">Moderate Messages</h2>
    <div class="chat-mod-list">
      <?php $modData = json_decode(file_get_contents($chatFile), true); if (!is_array($modData)) $modData = []; $modData = array_reverse(array_slice($modData, -80)); ?>
      <?php if (empty($modData)): ?>
        <p>No chat messages yet.</p>
      <?php else: foreach ($modData as $row): ?>
        <div class="chat-mod-row">
          <div class="chat-mod-copy">
            <div><strong><?= htmlspecialchars($row['name'] ?? 'Guest') ?></strong> <span style="opacity:.7;">(<?= htmlspecialchars($row['time'] ?? '') ?>)</span></div>
            <div style="opacity:.92;margin-top:4px;"><?= htmlspecialchars($row['msg'] ?? '') ?></div>
          </div>
          <form method="post" onsubmit="return confirm('Delete this message?');">
            <input type="hidden" name="delete_msg" value="1">
            <input type="hidden" name="delete_id" value="<?= htmlspecialchars($row['id'] ?? '') ?>">
            <button class="admin-btn" type="submit">Delete</button>
          </form>
        </div>
      <?php endforeach; endif; ?>
    </div>
  </div>

  <div class="content-card" style="text-align:left;">
    <h2 style="margin-top:0;">Post as Admin</h2>
    <form method="post">
      <input type="hidden" name="admin_send" value="1">
      <div class="request-field">
        <label>Display name</label>
        <input class="request-input" type="text" name="name" value="DJ Smurfette" maxlength="32">
      </div>
      <div class="request-field">
        <label>Message</label>
        <input id="adminMsg" class="request-input" type="text" name="msg" maxlength="240" placeholder="Type a message…">
      </div>

      <div class="chat-emoji">
        <button type="button" id="adminEmojiToggle" class="btn btn-accent btn-emoji">😊 Emojis</button>
        <div id="adminEmojiPanel" class="emoji-panel" aria-hidden="true">
          <div class="emoji-search-row">
            <input id="adminEmojiSearch" class="request-input emoji-search" type="text" placeholder="Search… (try: heart, music, smile)" maxlength="30">
            <button type="button" id="adminEmojiClose" class="btn btn-accent btn-emoji-close">Close</button>
          </div>
          <div id="adminEmojiGrid" class="emoji-grid"></div>
        </div>
      </div>

      <button class="btn btn-accent" type="submit">Send</button>
    </form>
  </div>

  <div class="content-card" style="text-align:left;">
    <h2 style="margin-top:0;">Moderation</h2>
    <form method="post" onsubmit="return confirm('Clear chat for everyone?');">
      <input type="hidden" name="clear_chat" value="1">
      <button class="btn btn-accent" type="submit">Clear Chat</button>
    </form>
  </div>

</div>
<?php include __DIR__ . '/includes/footer.php'; ?>


<script>
(function(){
  const box = document.getElementById('adminChatBox');
  if (!box) return;

  // emoji picker for admin message input
  const msgEl = document.getElementById('adminMsg');
  const emojiToggle = document.getElementById('adminEmojiToggle');
  const emojiPanel  = document.getElementById('adminEmojiPanel');
  const emojiGrid   = document.getElementById('adminEmojiGrid');
  const emojiSearch = document.getElementById('adminEmojiSearch');
  const emojiClose  = document.getElementById('adminEmojiClose');

  const EMOJIS = [
  // smileys
  ["😀","smile"],["😁","grin"],["😂","laugh"],["🤣","rofl"],["😊","happy"],["😍","love"],["🥰","love"],["😘","kiss"],["😎","cool"],["🤠","cowboy"],
  ["🙂","smile"],["😉","wink"],["😇","angel"],["🤩","star"],["🥳","party"],["😴","sleep"],["🤔","think"],["🙃","silly"],["😬","awkward"],["😭","cry"],
  ["😡","angry"],["😱","shock"],["🤗","hug"],["🤐","zip"],["🤫","shh"],["😜","tongue"],["😋","yum"],["😌","relief"],["🥺","please"],["😅","sweat"],
  // hearts
  ["❤️","heart"],["🧡","heart"],["💛","heart"],["💚","heart"],["💙","heart"],["💜","heart"],["🖤","heart"],["🤍","heart"],["🤎","heart"],["💖","sparkle"],
  ["💘","heart"],["💝","gift"],["💞","hearts"],["💕","hearts"],["💓","heart"],["💗","heart"],["💯","100"],
  // music
  ["🎵","music"],["🎶","music"],["🎧","headphones"],["🎤","mic"],["🎸","guitar"],["🎻","violin"],["🥁","drum"],["🎹","piano"],["📻","radio"],["🔊","loud"],
  // fire / hype
  ["🔥","fire"],["✨","sparkle"],["🌟","star"],["⚡","zap"],["💥","boom"],["👏","clap"],["🙌","yay"],["👍","thumbs up"],["👎","thumbs down"],["👌","ok"],
  // country / fun
  ["🤠","cowboy"],["🐎","horse"],["🌵","cactus"],["🏜️","desert"],["🪕","banjo"],["🥃","drink"],["🍻","cheers"],["🍔","burger"],["🍕","pizza"],
  // misc
  ["✅","check"],["❌","x"],["🕺","dance"],["💃","dance"],["🎉","party"],["🎁","gift"],["🏆","trophy"],["📣","megaphone"],["📝","note"],["📌","pin"],
  ["👀","eyes"],["🫶","hands"],["🙏","pray"],["🤝","shake"],["💬","chat"],["📢","announce"],["🔔","bell"],["⏰","clock"],["🌈","rainbow"],["☀️","sun"],
  ["🌙","moon"],["⭐","star"],["☕","coffee"],["🍀","luck"],["🎯","target"],["🚀","rocket"],["🧠","brain"],["🧡","heart"],["💙","heart"],["😺","cat"],
  ["🐶","dog"],["🐼","panda"],["🦊","fox"],["🐸","frog"],["🐵","monkey"],["🦋","butterfly"],["🌸","flower"],["🌻","flower"],["🌹","rose"],["🍁","leaf"],
  ["❄️","snow"],["🌊","wave"],["🏝️","island"],["🏕️","camp"],["🏠","home"],["🚗","car"],["✈️","plane"],["📸","photo"],["🎬","movie"],["📺","tv"]
];;

  const esc = (s)=> String(s||'').replace(/[&<>"']/g, c=>({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;' }[c]));

  function buildEmojiGrid(filterText){
    const q = (filterText || '').trim().toLowerCase();
    let html = '';
    for (const [emo, keys] of EMOJIS){
      if (!q || (keys && keys.toLowerCase().includes(q)) || emo.includes(q)){
        html += `<button type="button" class="emoji-pick" data-emo="${emo}">${emo}</button>`;
      }
    }
    emojiGrid.innerHTML = html || '<div style="opacity:.8;padding:8px;">No matches</div>';
  }
  function openEmoji(){
    emojiPanel.classList.add('open');
    emojiPanel.setAttribute('aria-hidden','false');
    buildEmojiGrid(emojiSearch.value);
    setTimeout(()=>emojiSearch.focus(), 0);
  }
  function closeEmoji(){
    emojiPanel.classList.remove('open');
    emojiPanel.setAttribute('aria-hidden','true');
  }

  emojiToggle?.addEventListener('click', ()=> {
    if (emojiPanel.classList.contains('open')) closeEmoji();
    else openEmoji();
  });
  emojiClose?.addEventListener('click', closeEmoji);
  emojiSearch?.addEventListener('input', ()=>buildEmojiGrid(emojiSearch.value));
  emojiGrid?.addEventListener('click', (e)=>{
    const btn = e.target.closest('.emoji-pick');
    if (!btn) return;
    const emo = btn.getAttribute('data-emo') || '';
    const start = msgEl.selectionStart ?? msgEl.value.length;
    const end   = msgEl.selectionEnd ?? msgEl.value.length;
    msgEl.value = msgEl.value.slice(0,start) + emo + msgEl.value.slice(end);
    msgEl.focus();
    msgEl.selectionStart = msgEl.selectionEnd = start + emo.length;
  });
  document.addEventListener('keydown', (e)=>{ if (e.key === 'Escape') closeEmoji(); });
  document.addEventListener('click', (e)=>{
    if (!emojiPanel || !emojiPanel.classList.contains('open')) return;
    if (emojiPanel.contains(e.target) || emojiToggle.contains(e.target)) return;
    closeEmoji();
  });

  // live feed
  let lastTs = 0;
  let pulling = false;

  function isAtBottom(el){ return (el.scrollTop + el.clientHeight) >= (el.scrollHeight - 20); }

  function render(messages){
    const atBottom = isAtBottom(box);
    let html = '';
    for (const m of (messages||[])){
      const cls = m.role === 'admin' ? 'chat-msg admin' : 'chat-msg';
      const who = esc(m.name || 'Guest');
      const t   = esc(m.time || '');
      const text = esc(m.msg || '');
      html += `<div class="${cls}"><div class="meta"><span class="who">${who}</span><span class="time">${t}</span></div><div class="text">${text}</div></div>`;
    }
    box.innerHTML = html;
    if (atBottom) box.scrollTop = box.scrollHeight;
  }

  async function pull(){
    if (pulling) return;
    pulling = true;
    try {
      const r = await fetch('/api/chat_get.php?since=' + encodeURIComponent(lastTs), {cache:'no-store'});
      const j = await r.json();
      if (j && j.ok) {
        lastTs = j.ts || lastTs;
        render(j.messages || []);
      }
    } catch(e) {}
    pulling = false;
  }

  pull();
  setInterval(pull, 2000);
})();
</script>

<?php include __DIR__ . '/includes/admin_footer.php'; ?>
