<?php
// modules/chat_group.php - repaired UI
if (!function_exists('e')) {
    function e($v): string { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
}
$currentName = $_SESSION['full_name'] ?? ($_SESSION['user']['full_name'] ?? $_SESSION['username'] ?? 'User');
?>
<style>
.chat-wrap{max-width:1120px;margin:0 auto}.chat-hero{border-radius:28px;background:linear-gradient(135deg,#14b8a6,#0284c7);color:white;padding:34px 38px;box-shadow:0 24px 55px rgba(2,132,199,.2);display:flex;justify-content:space-between;gap:20px;align-items:center;overflow:hidden}.chat-hero h2{font-size:32px;font-weight:900;margin:0}.chat-hero p{margin-top:8px;opacity:.95}.chat-login{background:rgba(255,255,255,.16);border:1px solid rgba(255,255,255,.26);border-radius:18px;padding:14px 18px;font-weight:800}.chat-card{margin-top:24px;background:white;border:1px solid #dbe3ef;border-radius:24px;box-shadow:0 18px 44px rgba(15,23,42,.08);overflow:hidden}.chat-head{display:flex;justify-content:space-between;align-items:center;padding:16px 20px;border-bottom:1px solid #e5e7eb}.chat-title{font-weight:900;color:#0f172a}.chat-sub{font-size:13px;color:#64748b}.chat-box{height:520px;overflow-y:auto;background:linear-gradient(135deg,#eefdfa,#f1f5ff);padding:18px}.bubble{max-width:68%;background:#fff;border-radius:18px;padding:12px 14px;margin:8px 0;box-shadow:0 10px 24px rgba(15,23,42,.06);line-height:1.45}.bubble.me{margin-left:auto;background:#d9f99d}.bubble .meta{font-size:12px;font-weight:900;color:#047857;margin-bottom:5px}.bubble .time{font-size:11px;color:#64748b;margin-top:6px}.chat-form{display:flex;gap:12px;padding:16px;background:white;border-top:1px solid #e5e7eb}.chat-input{flex:1;border:1px solid #cbd5e1;border-radius:16px;padding:13px 16px;font-size:15px;outline:none}.chat-input:focus{border-color:#14b8a6;box-shadow:0 0 0 4px rgba(20,184,166,.12)}.chat-send{width:58px;border:0;border-radius:16px;background:linear-gradient(135deg,#14b8a6,#0284c7);color:white;font-weight:900;cursor:pointer}.chat-refresh{border:0;border-radius:13px;background:#0f172a;color:white;padding:10px 15px;font-weight:800;cursor:pointer}.chat-error{text-align:center;color:#ef4444;padding:80px 20px}.chat-empty{text-align:center;color:#64748b;padding:80px 20px}@media(max-width:768px){.chat-hero{display:block}.chat-login{margin-top:15px}.bubble{max-width:88%}}
</style>
<div class="chat-wrap">
  <div class="chat-hero">
    <div>
      <div style="display:inline-flex;align-items:center;gap:8px;background:rgba(255,255,255,.14);border:1px solid rgba(255,255,255,.22);padding:8px 14px;border-radius:999px;font-weight:800;margin-bottom:14px">💬 Grup Internal</div>
      <h2>Chat Grup Keperawatan</h2>
      <p>Diskusi cepat seperti WA grup, lengkap dengan histori, popup, dan suara notifikasi.</p>
    </div>
    <div class="chat-login">LOGIN SEBAGAI<br><?= e($currentName) ?></div>
  </div>
  <div class="chat-card">
    <div class="chat-head">
      <div><div class="chat-title">Ruang Chat</div><div class="chat-sub">Pesan tersimpan sebagai chat history.</div></div>
      <button class="chat-refresh" onclick="loadChat(true)">↻ Refresh</button>
    </div>
    <div id="chatBox" class="chat-box"><div class="chat-empty">Memuat chat...</div></div>
    <form id="chatForm" class="chat-form" autocomplete="off">
      <input id="chatInput" class="chat-input" type="text" placeholder="Tulis pesan..." maxlength="4000">
      <button class="chat-send" type="submit">➤</button>
    </form>
  </div>
</div>
<script>
const chatBox = document.getElementById('chatBox');
const chatForm = document.getElementById('chatForm');
const chatInput = document.getElementById('chatInput');
let lastMaxId = 0;
let firstLoad = true;
function esc(s){return String(s ?? '').replace(/[&<>'"]/g, m=>({'&':'&amp;','<':'&lt;','>':'&gt;',"'":'&#39;','"':'&quot;'}[m]));}
function timeLabel(v){ if(!v) return ''; const d = new Date(String(v).replace(' ', 'T')); return isNaN(d) ? v : d.toLocaleString('id-ID',{day:'2-digit',month:'2-digit',hour:'2-digit',minute:'2-digit'}); }
function beep(){ try{ const ctx = new (window.AudioContext||window.webkitAudioContext)(); const o=ctx.createOscillator(); const g=ctx.createGain(); o.type='sine'; o.frequency.setValueAtTime(880,ctx.currentTime); o.frequency.exponentialRampToValueAtTime(1320,ctx.currentTime+.12); g.gain.setValueAtTime(.0001,ctx.currentTime); g.gain.exponentialRampToValueAtTime(.22,ctx.currentTime+.02); g.gain.exponentialRampToValueAtTime(.0001,ctx.currentTime+.35); o.connect(g); g.connect(ctx.destination); o.start(); o.stop(ctx.currentTime+.36);}catch(e){} }
async function loadChat(manual=false){
  try{
    const res = await fetch('chat_api.php?action=list&limit=250&_=' + Date.now(), {credentials:'same-origin'});
    const text = await res.text(); let json;
    try { json = JSON.parse(text); } catch(e){ throw new Error('Response bukan JSON: ' + text.substring(0,180)); }
    if(!json.ok) throw new Error(json.detail || json.error || 'API error');
    const messages = json.messages || json.data || [];
    if(messages.length === 0){ chatBox.innerHTML = '<div class="chat-empty">Belum ada chat. Mulai diskusi pertama.</div>'; return; }
    const maxId = Math.max(...messages.map(m=>Number(m.id)||0));
    const shouldNotify = !firstLoad && maxId > lastMaxId && !manual;
    chatBox.innerHTML = messages.map(m=>{
      const me = m.is_me ? ' me' : '';
      const source = m.source === 'telegram' ? ' · telegram' : '';
      return `<div class="bubble${me}"><div class="meta">${esc(m.user_name)} <span style="color:#64748b;font-weight:700">· ${esc(m.user_role)}${source}</span></div><div>${esc(m.message).replace(/\n/g,'<br>')}</div><div class="time">${esc(timeLabel(m.created_at))}</div></div>`;
    }).join('');
    chatBox.scrollTop = chatBox.scrollHeight;
    if(shouldNotify) beep();
    lastMaxId = maxId; firstLoad = false;
    fetch('chat_api.php?action=mark_read', {credentials:'same-origin'}).catch(()=>{});
  }catch(err){
    chatBox.innerHTML = `<div class="chat-error">Chat belum bisa dimuat: ${esc(err.message)}</div>`;
    console.error(err);
  }
}
chatForm.addEventListener('submit', async (e)=>{
  e.preventDefault();
  const msg = chatInput.value.trim(); if(!msg) return;
  const fd = new FormData(); fd.append('action','send'); fd.append('message',msg);
  chatInput.value='';
  try{
    const res = await fetch('chat_api.php', {method:'POST', body:fd, credentials:'same-origin'});
    const json = await res.json();
    if(!json.ok) throw new Error(json.detail || json.error || 'Gagal kirim');
    await loadChat(true);
  }catch(err){ alert('Gagal kirim chat: ' + err.message); }
});
loadChat(true); setInterval(()=>loadChat(false), 5000);
</script>
