
<?php
// اتصال قاعدة البيانات ولغة الواجهة يُؤخذان من جلسة لوحة الفندق.
if (!isset($pdo) || !($pdo instanceof PDO)) {
    @include_once __DIR__ . '/../../api/db_connect.php';
}
require_once __DIR__ . '/../../api/lib/ai_page_context.php';

$aiCurrentPageKey = basename((string)(parse_url((string)($_SERVER['SCRIPT_NAME'] ?? ''), PHP_URL_PATH) ?: ''));
$aiCurrentUserRole = (string)($_SESSION['user_role'] ?? '');
$aiWidgetLanguage = eth_ai_language_code((string)($_SESSION['pms_language'] ?? 'ar'));
$aiWidgetDirection = in_array($aiWidgetLanguage, ['en', 'fr', 'es'], true) ? 'ltr' : 'rtl';
$aiWidgetPdo = (isset($pdo) && $pdo instanceof PDO) ? $pdo : null;

$aiCurrentPageContext = [
    'page_key' => '',
    'page_title' => 'لوحة إدارة الفندق',
    'page_url' => '',
    'content' => 'يمكنني إرشادك إلى صفحات إدارة الفندق وشرح الخطوات الموثقة.',
];
try {
    if ($aiWidgetPdo instanceof PDO) {
        $aiCurrentPageContext = eth_ai_resolve_page_context($aiWidgetPdo, $aiCurrentPageKey, $aiCurrentUserRole);
    }
} catch (Throwable $e) {
    error_log('ETHAR_AI_WIDGET_PAGE_CONTEXT: ' . $e->getMessage());
}

$aiWidgetJsSources = [
    'open' => 'إظهار المساعد الإداري',
    'close' => 'إغلاق المساعد الإداري',
    'assistant' => 'المساعد الإداري',
    'openPage' => 'فتح الصفحة',
    'relatedPages' => 'صفحات مرتبطة',
    'page' => 'صفحة',
    'remaining' => 'المتبقي هذا الشهر:',
    'quotaEnded' => 'انتهت حصة المساعد الشهرية',
    'quotaRenewal' => 'تتجدد الحصة مع بداية الشهر القادم، أو يمكنك مراجعة خيارات الترقية.',
    'reviewPlan' => 'مراجعة الباقة',
    'freeNavigation' => 'لا يزال بإمكانك طلب روابط الصفحات والتنقل بينها دون استهلاك حصة AI.',
    'genericError' => 'عذراً، تعذر الحصول على إجابة الآن. حاول مرة أخرى لاحقاً.',
    'connectionError' => 'فشل الاتصال بالخادم.',
];
$aiWidgetQuickSources = [
    'what_page' => 'ما وظيفة هذه الصفحة؟',
    'create_booking' => 'كيف أقوم بعمل حجز جديد؟',
    'checkin' => 'كيف أنفذ تسكين نزيل لحجز موجود؟',
    'checkout' => 'كيف أسجل مغادرة النزيل؟',
    'transfer' => 'كيف أنقل النزيل إلى غرفة أخرى؟',
];
$aiWidgetHtmlSources = [
    'إظهار المساعد الإداري', 'إغلاق المساعد الإداري', 'المساعد الإداري', 'المساعد الإداري الذكي',
    'مرحباً! 👋 أنت الآن في صفحة', 'يمكنني شرح وظيفة الصفحة أو إرشادك إلى الصفحة المناسبة لتنفيذ مهمة أخرى.',
    'اشرح الصفحة الحالية', 'كيف أنشئ حجزاً؟', 'تسكين نزيل', 'مغادرة نزيل', 'نقل غرفة',
    'المساعد الإداري غير متاح حالياً', 'انتهت حصتك الشهرية', 'من', 'سؤالاً',
    'تتجدد الحصة مع بداية الشهر القادم.',
    'هذه الميزة غير متاحة ضمن باقتك الحالية. يمكنك ترقية الباقة لتفعيل المساعد الإداري.',
    'مراجعة الباقة', 'جاري التفكير...', 'اكتب سؤالك هنا...',
];
$aiPageCatalog = eth_ai_admin_page_catalog();
$aiWidgetSources = array_values(array_unique(array_merge(
    $aiWidgetHtmlSources,
    array_values($aiWidgetJsSources),
    array_values($aiWidgetQuickSources),
    array_map(static fn(array $item): string => (string)($item['title'] ?? ''), $aiPageCatalog),
    [(string)($aiCurrentPageContext['page_title'] ?? 'لوحة إدارة الفندق'), 'لوحة إدارة الفندق']
)));
$aiWidgetTranslations = [];
if ($aiWidgetLanguage !== 'ar' && $aiWidgetPdo instanceof PDO && $aiWidgetSources) {
    try {
        $sourceHashMap = [];
        foreach ($aiWidgetSources as $source) {
            if ($source !== '') $sourceHashMap[hash('sha256', $source)] = $source;
        }
        $hashes = array_keys($sourceHashMap);
        if ($hashes) {
            $placeholders = implode(',', array_fill(0, count($hashes), '?'));
            $query = $aiWidgetPdo->prepare(
                "SELECT translation_key, source_text, translation_value
                 FROM Translation
                 WHERE language_code = ? AND translation_key IN ($placeholders)"
            );
            $query->execute(array_merge([$aiWidgetLanguage], $hashes));
            foreach ($query->fetchAll(PDO::FETCH_ASSOC) as $row) {
                $source = (string)($row['source_text'] ?? '');
                $value = (string)($row['translation_value'] ?? '');
                if ($source !== '' && $value !== '' && isset($sourceHashMap[(string)$row['translation_key']])) {
                    $aiWidgetTranslations[$source] = $value;
                }
            }
        }
    } catch (Throwable $e) {
        error_log('ETHAR_AI_WIDGET_TRANSLATIONS: ' . $e->getMessage());
    }
}
$aiWidgetT = static fn(string $source): string => (string)($aiWidgetTranslations[$source] ?? $source);

$aiPageTitleSource = (string)($aiCurrentPageContext['page_title'] ?? 'لوحة إدارة الفندق');
$aiPageTitleLocalized = $aiWidgetT($aiPageTitleSource);
if ($aiPageTitleLocalized === $aiPageTitleSource && isset($aiPageCatalog[$aiCurrentPageKey]['title'])) {
    $aiPageTitleLocalized = $aiWidgetT((string)$aiPageCatalog[$aiCurrentPageKey]['title']);
}
$aiCurrentPageContext['page_title'] = $aiPageTitleLocalized;

$aiAdminAvailable = false;
$aiAdminUsage = ['quota' => 0, 'used' => 0, 'remaining' => 0, 'plan_code' => 'free'];
try {
    if ($aiWidgetPdo instanceof PDO && !empty($_SESSION['active_property_id'])) {
        require_once __DIR__ . '/feature_gate.php';
        $propertyId = (int)$_SESSION['active_property_id'];
        $aiAdminUsage = pms_feature_gate_usage_info($aiWidgetPdo, $propertyId, 'ai_admin');
        $aiAdminAvailable = !empty($aiAdminUsage['allowed']);
    }
} catch (Throwable $e) {
    $aiAdminAvailable = false;
    error_log('ETHAR_AI_WIDGET_QUOTA_CHECK: ' . $e->getMessage());
}

$aiWidgetJsText = [];
foreach ($aiWidgetJsSources as $key => $source) $aiWidgetJsText[$key] = $aiWidgetT($source);
$aiWidgetJsJson = json_encode($aiWidgetJsText, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT);
if (!is_string($aiWidgetJsJson)) $aiWidgetJsJson = '{}';
$aiWidgetQuickPrompts = [];
foreach ($aiWidgetQuickSources as $key => $source) {
    $aiWidgetQuickPrompts[$key] = json_encode($aiWidgetT($source), JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
}
$aiWidgetIntro = $aiWidgetT('مرحباً! 👋 أنت الآن في صفحة');
$aiWidgetIntroHelp = $aiWidgetT('يمكنني شرح وظيفة الصفحة أو إرشادك إلى الصفحة المناسبة لتنفيذ مهمة أخرى.');
?>

<!-- واجهة المساعد الإداري الذكي -->
<style>
    /* زر صغير ثابت في منتصف يسار الشاشة حتى لا يغطي محتوى الصفحة. */
    .ai-widget-btn {
        position: fixed;
        left: 12px;
        top: 50%;
        transform: translateY(-50%);
        width: 46px;
        height: 46px;
        padding: 0;
        background: linear-gradient(135deg, #1a73e8, #8b5cf6);
        color: white;
        border: 0;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 18px;
        box-shadow: 0 6px 18px rgba(0,0,0,.22);
        cursor: pointer;
        z-index: 100001;
        transition: transform .2s, opacity .2s;
        font-family: 'Cairo', sans-serif;
    }
    .ai-widget-btn:hover { transform: translateY(-50%) scale(1.06); }

    .ai-chat-window {
        position: fixed;
        top: 50%;
        bottom: auto;
        left: 68px;
        transform: translateY(-50%);
        width: 350px;
        height: 500px;
        background: white;
        border-radius: 12px;
        box-shadow: 0 10px 30px rgba(0,0,0,0.15);
        display: none;
        flex-direction: column;
        z-index: 9999;
        overflow: hidden;
        border: 1px solid #e2e8f0;
        font-family: 'Cairo', sans-serif;
        direction: <?= $aiWidgetDirection ?>;
        text-align: start;
    }
    .ai-chat-header {
        background: linear-gradient(135deg, #1a73e8, #8b5cf6);
        color: white;
        padding: 15px;
        font-weight: bold;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .ai-chat-close { cursor: pointer; font-size: 18px; }
    .ai-chat-body {
        flex: 1;
        padding: 15px;
        direction: <?= $aiWidgetDirection ?>;
        text-align: start;
        overflow-y: auto;
        background: #f8fafc;
        display: flex;
        flex-direction: column;
        gap: 10px;
    }
    .ai-msg { max-width: 85%; padding: 10px 15px; border-radius: 8px; font-size: 14px; line-height: 1.6; }
    .ai-msg-bot { background: white; border: 1px solid #e2e8f0; align-self: flex-start; border-bottom-right-radius: 0; color: #1e293b; }
    .ai-msg-user { background: #1a73e8; color: white; align-self: flex-end; border-bottom-left-radius: 0; }
    .ai-chat-footer {
        padding: 10px;
        background: white;
        border-top: 1px solid #e2e8f0;
        display: flex;
        gap: 10px;
    }
    .ai-chat-input {
        flex: 1;
        padding: 10px;
        border: 1px solid #cbd5e1;
        border-radius: 20px;
        outline: none;
        font-family: inherit;
        direction: <?= $aiWidgetDirection ?>;
        text-align: start;
    }
    .ai-chat-send {
        background: #1a73e8;
        color: white;
        border: none;
        width: 40px;
        height: 40px;
        border-radius: 50%;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .ai-chat-send:disabled { background: #94a3b8; }
    .typing-indicator { font-size: 12px; color: #64748b; display: none; margin-top: 5px; }

    .ai-paywall {
        background: linear-gradient(135deg, #fff, #faf5fc);
        border: 1px solid #eadff0;
        color: #5b3a70;
        align-self: flex-start;
        border-bottom-right-radius: 0;
    }
    .ai-paywall strong { display:block; margin-bottom:4px; color:#4b2b63; }
    @media (max-width: 600px) {
        .ai-widget-btn { left: 8px; width: 42px; height: 42px; }
        .ai-chat-window { left: 8px; right: 8px; width: auto; height: min(520px, 72vh); }
    }

    .ai-quick-actions { display:flex; flex-wrap:wrap; gap:6px; margin:0 2px 4px; }
    .ai-quick-actions button { border:1px solid #ddd1e9; background:#fff; color:#5b3280; border-radius:16px; padding:6px 9px; font:inherit; font-size:11px; cursor:pointer; }
    .ai-quick-actions button:hover { background:#f3edf8; }
    .ai-page-link a,.ai-sources a { color:#5b3280; font-weight:800; text-decoration:underline; }
    .ai-page-link { margin-top:9px; padding:8px 10px; border-radius:9px; background:#f3edf8; }
    .ai-sources { margin-top:8px; padding-top:7px; border-top:1px solid #e2e8f0; font-size:11px; color:#64748b; }
    .ai-paywall a {
        display:inline-flex;
        margin-top:9px;
        padding:8px 11px;
        border-radius:9px;
        background:#6b3c8e;
        color:#fff;
        text-decoration:none;
        font-size:11px;
        font-weight:900;
    }
</style>

<!-- زر الودجيت الجديد الذي يحتوي على الأيقونة والنص معاً -->
<button type="button" class="ai-widget-btn" onclick="toggleAiChat()" aria-label="<?= htmlspecialchars($aiWidgetT('إظهار المساعد الإداري'), ENT_QUOTES, 'UTF-8') ?>" title="<?= htmlspecialchars($aiWidgetT('المساعد الإداري'), ENT_QUOTES, 'UTF-8') ?>">
    <i class="fa-solid fa-user-tie"></i>
</button>

<div class="ai-chat-window" id="aiChatWindow" dir="<?= $aiWidgetDirection ?>">
    <div class="ai-chat-header">
        <span><i class="fa-solid fa-user-tie"></i> <?= htmlspecialchars($aiWidgetT('المساعد الإداري الذكي'), ENT_QUOTES, 'UTF-8') ?></span>
        <i class="fa-solid fa-xmark ai-chat-close" onclick="toggleAiChat()"></i>
    </div>
    <div class="ai-chat-body" id="aiChatBody">
        <div class="ai-msg ai-msg-bot ai-page-intro">
            <?= htmlspecialchars($aiWidgetIntro, ENT_QUOTES, 'UTF-8') ?> <strong><?= htmlspecialchars((string)$aiCurrentPageContext['page_title'], ENT_QUOTES, 'UTF-8') ?></strong>.
            <?= htmlspecialchars($aiWidgetIntroHelp, ENT_QUOTES, 'UTF-8') ?>
        </div>
        <div class="ai-quick-actions">
            <button type="button" onclick='sendAiQuickPrompt(<?= $aiWidgetQuickPrompts['what_page'] ?>)'><?= htmlspecialchars($aiWidgetT('اشرح الصفحة الحالية'), ENT_QUOTES, 'UTF-8') ?></button>
            <button type="button" onclick='sendAiQuickPrompt(<?= $aiWidgetQuickPrompts['create_booking'] ?>)'><?= htmlspecialchars($aiWidgetT('كيف أنشئ حجزاً؟'), ENT_QUOTES, 'UTF-8') ?></button>
            <button type="button" onclick='sendAiQuickPrompt(<?= $aiWidgetQuickPrompts['checkin'] ?>)'><?= htmlspecialchars($aiWidgetT('تسكين نزيل'), ENT_QUOTES, 'UTF-8') ?></button>
            <button type="button" onclick='sendAiQuickPrompt(<?= $aiWidgetQuickPrompts['checkout'] ?>)'><?= htmlspecialchars($aiWidgetT('مغادرة نزيل'), ENT_QUOTES, 'UTF-8') ?></button>
            <button type="button" onclick='sendAiQuickPrompt(<?= $aiWidgetQuickPrompts['transfer'] ?>)'><?= htmlspecialchars($aiWidgetT('نقل غرفة'), ENT_QUOTES, 'UTF-8') ?></button>
        </div>
        <?php if(!$aiAdminAvailable): ?>
        <div class="ai-msg ai-msg-bot ai-paywall">
            <strong>🔒 <?= htmlspecialchars($aiWidgetT('المساعد الإداري غير متاح حالياً'), ENT_QUOTES, 'UTF-8') ?></strong>
            <?php if (($aiAdminUsage['quota'] ?? 0) > 0): ?>
                <?= htmlspecialchars($aiWidgetT('انتهت حصتك الشهرية'), ENT_QUOTES, 'UTF-8') ?> (<?= (int)($aiAdminUsage['used'] ?? 0) ?> <?= htmlspecialchars($aiWidgetT('من'), ENT_QUOTES, 'UTF-8') ?> <?= (int)$aiAdminUsage['quota'] ?> <?= htmlspecialchars($aiWidgetT('سؤالاً'), ENT_QUOTES, 'UTF-8') ?>). <?= htmlspecialchars($aiWidgetT('تتجدد الحصة مع بداية الشهر القادم.'), ENT_QUOTES, 'UTF-8') ?>
            <?php else: ?>
                <?= htmlspecialchars($aiWidgetT('هذه الميزة غير متاحة ضمن باقتك الحالية. يمكنك ترقية الباقة لتفعيل المساعد الإداري.'), ENT_QUOTES, 'UTF-8') ?>
            <?php endif; ?>
            <a href="subscription.php"><?= htmlspecialchars($aiWidgetT('مراجعة الباقة'), ENT_QUOTES, 'UTF-8') ?></a>
        </div>
        <?php endif; ?>
    </div>
    <div style="padding: 0 15px;"><span class="typing-indicator" id="aiTyping"><?= htmlspecialchars($aiWidgetT('جاري التفكير...'), ENT_QUOTES, 'UTF-8') ?></span></div>
    <div class="ai-chat-footer">
        <input type="text" id="aiChatInput" class="ai-chat-input" placeholder="<?= htmlspecialchars($aiWidgetT('اكتب سؤالك هنا...'), ENT_QUOTES, 'UTF-8') ?>" onkeypress="handleAiEnter(event)">
        <button id="aiChatSend" class="ai-chat-send" onclick="sendAiMessage()"><i class="fa-solid fa-paper-plane"></i></button>
    </div>
</div>

<script>
    const aiWidgetText = <?= $aiWidgetJsJson ?>;
    window.PMS_AI_WIDGET_PRO = <?= (($aiAdminUsage['plan_code'] ?? '') === 'pro') ? 'true' : 'false' ?>;
    window.PMS_AI_WIDGET_AVAILABLE = <?= $aiAdminAvailable ? 'true' : 'false' ?>;
    window.PMS_AI_PAGE_CONTEXT = <?= json_encode([
        'page_key' => (string)($aiCurrentPageContext['page_key'] ?? ''),
        'page_title' => (string)($aiCurrentPageContext['page_title'] ?? 'لوحة إدارة الفندق'),
        'page_url' => (string)($aiCurrentPageContext['page_url'] ?? ''),
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) ?>;

    function aiEscapeHtml(value) {
        return String(value ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#039;');
    }
    function aiSafeInternalUrl(value) {
        const url = String(value || '');
        return /^\/property-admin\/[a-zA-Z0-9_-]+\.php$/.test(url) && !url.includes('..') ? url : '';
    }
    function aiAppendReply(reply, link, sources, quota) {
        const formatted = aiEscapeHtml(reply).replace(/\n/g, '<br>');
        let html = `<div class="ai-msg ai-msg-bot">${formatted}`;
        const safeLink = link && aiSafeInternalUrl(link.url) ? link : null;
        if (safeLink) {
            html += `<div class="ai-page-link"><a href="${aiSafeInternalUrl(safeLink.url)}">${aiEscapeHtml(safeLink.title || aiWidgetText.openPage)}</a></div>`;
        }
        const safeSources = Array.isArray(sources) ? sources.filter(x => x && aiSafeInternalUrl(x.url)) : [];
        if (safeSources.length) {
            html += '<div class="ai-sources">' + aiWidgetText.relatedPages + ': ' + safeSources.slice(0, 2).map(x => `<a href="${aiSafeInternalUrl(x.url)}">${aiEscapeHtml(x.title || aiWidgetText.page)}</a>`).join(' · ') + '</div>';
        }
        if (quota && Number.isFinite(Number(quota.remaining))) {
            html += `<div style="margin-top:6px;font-size:11px;color:#64748b;">${aiWidgetText.remaining} ${Number(quota.remaining)}</div>`;
        }
        html += '</div>';
        document.getElementById('aiChatBody').insertAdjacentHTML('beforeend', html);
    }

    function toggleAiChat() {
        const chat = document.getElementById('aiChatWindow');
        const launcher = document.querySelector('.ai-widget-btn');
        const opening = chat.style.display !== 'flex';
        chat.style.display = opening ? 'flex' : 'none';
        if (launcher) {
            launcher.setAttribute('aria-label', opening ? <?= json_encode($aiWidgetT('إغلاق المساعد الإداري'), JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) ?> : <?= json_encode($aiWidgetT('إظهار المساعد الإداري'), JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) ?>);
            launcher.title = opening ? <?= json_encode($aiWidgetT('إغلاق المساعد الإداري'), JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) ?> : <?= json_encode($aiWidgetT('المساعد الإداري'), JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) ?>;
            launcher.style.opacity = opening ? '0.78' : '1';
        }
    }

    function handleAiEnter(e) {
        if (e.key === 'Enter') sendAiMessage();
    }
    function sendAiQuickPrompt(prompt) {
        const input = document.getElementById('aiChatInput');
        if (!input) return;
        input.value = String(prompt || '');
        sendAiMessage();
    }

    async function sendAiMessage() {
        const input = document.getElementById('aiChatInput');
        const text = input.value.trim();
        if (!text) return;

        const chatBody = document.getElementById('aiChatBody');
        const sendBtn = document.getElementById('aiChatSend');
        const typing = document.getElementById('aiTyping');

        const safeText = String(text)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');

        chatBody.innerHTML += `<div class="ai-msg ai-msg-user">${safeText}</div>`;
        input.value = '';
        chatBody.scrollTop = chatBody.scrollHeight;

        /* The API handles free local navigation intents before checking AI quota. */
        /* Enabled plans use the centralized quota-checked AI endpoint. */
        sendBtn.disabled = true;
        typing.style.display = 'block';

        try {
            const response = await fetch('../api/admin/ai_assistant.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ message: text, page_key: (window.PMS_AI_PAGE_CONTEXT || {}).page_key || '' })
            });
            const data = await response.json();
            if (!response.ok && data.status !== 'upgrade_required' && data.status !== 'error') throw new Error('HTTP ' + response.status);

            typing.style.display = 'none';
            sendBtn.disabled = false;

            if (data.status === 'local') {
                aiAppendReply(data.reply || '', data.link || null, [], null);
            } else if (data.status === 'success') {
                aiAppendReply(data.reply || '', null, data.knowledge_sources || [], data.quota || null);
            } else if (data.status === 'upgrade_required') {
                chatBody.innerHTML += `<div class="ai-msg ai-msg-bot ai-paywall"><strong>${aiWidgetText.quotaEnded}</strong>${aiWidgetText.quotaRenewal}<br><a href="subscription.php">${aiWidgetText.reviewPlan}</a><div style="margin-top:6px;font-size:11px">${aiWidgetText.freeNavigation}</div></div>`;
            } else {
                chatBody.innerHTML += `<div class="ai-msg ai-msg-bot" style="color:red;">${aiWidgetText.genericError}</div>`;
            }
            chatBody.scrollTop = chatBody.scrollHeight;
        } catch (error) {
            typing.style.display = 'none';
            sendBtn.disabled = false;
            chatBody.innerHTML += `<div class="ai-msg ai-msg-bot" style="color:red;">${aiWidgetText.connectionError}</div>`;
            chatBody.scrollTop = chatBody.scrollHeight;
        }
    }</script>