<?php
// includes/chat_notifier.php
// Floating chat button + popup/sound notification.
// Aman dipanggil dari index.php sebelum </body>.

if (!function_exists('chat_notifier_current_module')) {
    function chat_notifier_current_module(): string
    {
        return trim((string)($_GET['module'] ?? 'dashboard'));
    }
}

$currentChatModule = chat_notifier_current_module();
?>
<style>
#bm-chat-float-wrap {
    position: fixed !important;
    right: 22px !important;
    bottom: 22px !important;
    z-index: 2147483000 !important;
    pointer-events: auto !important;
}
#bm-chat-float-btn {
    position: relative !important;
    display: inline-flex !important;
    align-items: center !important;
    gap: 10px !important;
    padding: 14px 18px !important;
    border-radius: 999px !important;
    background: linear-gradient(135deg, #10b981, #0ea5e9) !important;
    color: #fff !important;
    text-decoration: none !important;
    font-weight: 800 !important;
    box-shadow: 0 18px 35px rgba(14, 165, 233, 0.28) !important;
    border: 0 !important;
    cursor: pointer !important;
    pointer-events: auto !important;
}
#bm-chat-float-btn:hover { transform: translateY(-2px); filter: brightness(1.03); }
#bm-chat-float-badge {
    position: absolute;
    top: -7px;
    right: -7px;
    min-width: 24px;
    height: 24px;
    padding: 0 7px;
    border-radius: 999px;
    background: #ef4444;
    color: white;
    font-size: 12px;
    font-weight: 900;
    display: none;
    align-items: center;
    justify-content: center;
    box-shadow: 0 12px 20px rgba(239, 68, 68, .28);
}
#bm-chat-toast {
    position: fixed;
    right: 22px;
    bottom: 86px;
    z-index: 2147482999;
    width: min(360px, calc(100vw - 44px));
    background: rgba(15, 23, 42, .96);
    color: white;
    border-radius: 20px;
    padding: 14px 16px;
    box-shadow: 0 22px 50px rgba(15,23,42,.22);
    display: none;
    border: 1px solid rgba(255,255,255,.12);
}
#bm-chat-toast .t1 { font-weight: 900; font-size: 14px; margin-bottom: 3px; }
#bm-chat-toast .t2 { font-size: 13px; opacity: .85; }
@media(max-width: 640px) {
    #bm-chat-float-wrap { right: 14px !important; bottom: 14px !important; }
    #bm-chat-float-btn span { display: none; }
    #bm-chat-float-btn { width: 58px !important; height: 58px !important; justify-content:center !important; padding: 0 !important; }
}
</style>

<div id="bm-chat-toast">
    <div class="t1">Chat baru masuk</div>
    <div class="t2">Ada pesan baru di Chat Grup Keperawatan.</div>
</div>

<div id="bm-chat-float-wrap">
    <a id="bm-chat-float-btn"
       href="index.php?module=chat_group"
       title="Buka Chat Grup Keperawatan"
       aria-label="Buka Chat Grup Keperawatan">
        <i class="fas fa-comments"></i>
        <span>Chat</span>
        <b id="bm-chat-float-badge">0</b>
    </a>
</div>

<script>
(function(){
    const isChatPage = <?= json_encode($currentChatModule === 'chat_group') ?>;
    const badge = document.getElementById('bm-chat-float-badge');
    const toast = document.getElementById('bm-chat-toast');
    let lastMaxId = parseInt(localStorage.getItem('bmChatLastMaxId') || '0', 10) || 0;
    let audioUnlocked = false;

    function unlockAudio(){
        audioUnlocked = true;
        document.removeEventListener('click', unlockAudio);
        document.removeEventListener('touchstart', unlockAudio);
    }
    document.addEventListener('click', unlockAudio);
    document.addEventListener('touchstart', unlockAudio);

    function playModernChime(){
        try {
            const AudioCtx = window.AudioContext || window.webkitAudioContext;
            if (!AudioCtx) return;
            const ctx = new AudioCtx();
            const now = ctx.currentTime;
            const master = ctx.createGain();
            master.gain.setValueAtTime(0.0001, now);
            master.gain.exponentialRampToValueAtTime(0.18, now + 0.015);
            master.gain.exponentialRampToValueAtTime(0.0001, now + 1.05);
            master.connect(ctx.destination);

            [987.77, 1318.51, 1760.00].forEach((freq, i) => {
                const osc = ctx.createOscillator();
                const gain = ctx.createGain();
                osc.type = 'sine';
                osc.frequency.setValueAtTime(freq, now + i * 0.075);
                gain.gain.setValueAtTime(0.0001, now + i * 0.075);
                gain.gain.exponentialRampToValueAtTime(0.45 / (i + 1), now + i * 0.075 + 0.03);
                gain.gain.exponentialRampToValueAtTime(0.0001, now + 0.65 + i * 0.10);
                osc.connect(gain);
                gain.connect(master);
                osc.start(now + i * 0.075);
                osc.stop(now + 1.1);
            });
        } catch(e) {}
    }

    function showToast(unread){
        if (!toast) return;
        toast.querySelector('.t2').textContent = unread + ' pesan belum dibaca di Chat Grup Keperawatan.';
        toast.style.display = 'block';
        setTimeout(() => { toast.style.display = 'none'; }, 4500);
    }

    function setBadge(unread){
        unread = parseInt(unread || 0, 10) || 0;
        if (!badge) return;
        if (unread > 0) {
            badge.textContent = unread > 99 ? '99+' : unread;
            badge.style.display = 'flex';
        } else {
            badge.style.display = 'none';
        }
    }

    async function pollUnread(){
        try {
            const res = await fetch('chat_api.php?action=unread_count&_=' + Date.now(), {credentials: 'same-origin'});
            if (!res.ok) return;
            const data = await res.json();
            if (!data.ok) return;

            const unread = parseInt(data.unread || 0, 10) || 0;
            const maxId = parseInt(data.max_id || 0, 10) || 0;
            setBadge(unread);

            if (!isChatPage && unread > 0 && maxId > lastMaxId) {
                showToast(unread);
                playModernChime();
            }

            if (maxId > lastMaxId) {
                lastMaxId = maxId;
                localStorage.setItem('bmChatLastMaxId', String(lastMaxId));
            }
        } catch(e) {}
    }

    pollUnread();
    setInterval(pollUnread, 7000);
})();
</script>
