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

$aiAdminAvailable = false;
$aiAdminUsage = ['quota' => 0, 'used' => 0, 'remaining' => 0, 'plan_code' => 'free'];
try {
    if (isset($pdo) && $pdo 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($pdo, $propertyId, 'ai_admin');
        $aiAdminAvailable = !empty($aiAdminUsage['allowed']);
    }
} catch (Throwable $e) {
    $aiAdminAvailable = false;
    error_log('ETHAR_AI_WIDGET_QUOTA_CHECK: ' . $e->getMessage());
}

?>

<!-- واجهة المساعد الإداري الذكي -->
<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;
    }
    .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;
        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;
    }
    .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="إظهار المساعد الإداري" title="المساعد الإداري">
    <i class="fa-solid fa-user-tie"></i>
</button>

<div class="ai-chat-window" id="aiChatWindow">
    <div class="ai-chat-header">
        <span><i class="fa-solid fa-user-tie"></i> المساعد الإداري الذكي</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">
            مرحباً! 👋 أنت الآن في صفحة <strong><?= htmlspecialchars((string)$aiCurrentPageContext['page_title'], ENT_QUOTES, 'UTF-8') ?></strong>.
            يمكنني شرح وظيفة الصفحة أو إرشادك إلى الصفحة المناسبة لتنفيذ مهمة أخرى.
        </div>
        <div class="ai-quick-actions">
            <button type="button" onclick="sendAiQuickPrompt('ما وظيفة هذه الصفحة؟')">اشرح الصفحة الحالية</button>
            <button type="button" onclick="sendAiQuickPrompt('كيف أقوم بعمل حجز جديد؟')">كيف أنشئ حجزاً؟</button>
            <button type="button" onclick="sendAiQuickPrompt('كيف أنفذ تسكين نزيل لحجز موجود؟')">تسكين نزيل</button>
            <button type="button" onclick="sendAiQuickPrompt('كيف أسجل مغادرة النزيل؟')">مغادرة نزيل</button>
            <button type="button" onclick="sendAiQuickPrompt('كيف أنقل النزيل إلى غرفة أخرى؟')">نقل غرفة</button>
        </div>
        <?php if(!$aiAdminAvailable): ?>
        <div class="ai-msg ai-msg-bot ai-paywall">
            <strong>🔒 المساعد الإداري غير متاح حالياً</strong>
            <?php if (($aiAdminUsage['quota'] ?? 0) > 0): ?>
                انتهت حصتك الشهرية (<?= (int)($aiAdminUsage['used'] ?? 0) ?> من <?= (int)$aiAdminUsage['quota'] ?> سؤالاً). تتجدد الحصة مع بداية الشهر القادم.
            <?php else: ?>
                هذه الميزة غير متاحة ضمن باقتك الحالية. يمكنك ترقية الباقة لتفعيل المساعد الإداري.
            <?php endif; ?>
            <a href="subscription.php">مراجعة الباقة</a>
        </div>
        <?php endif; ?>
    </div>
    <div style="padding: 0 15px;"><span class="typing-indicator" id="aiTyping">جاري التفكير...</span></div>
    <div class="ai-chat-footer">
        <input type="text" id="aiChatInput" class="ai-chat-input" placeholder="اكتب سؤالك هنا..." onkeypress="handleAiEnter(event)">
        <button id="aiChatSend" class="ai-chat-send" onclick="sendAiMessage()"><i class="fa-solid fa-paper-plane"></i></button>
    </div>
</div>

<script>
    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 || 'فتح الصفحة')}</a></div>`;
        }
        const safeSources = Array.isArray(sources) ? sources.filter(x => x && aiSafeInternalUrl(x.url)) : [];
        if (safeSources.length) {
            html += '<div class="ai-sources">صفحات مرتبطة: ' + safeSources.slice(0, 2).map(x => `<a href="${aiSafeInternalUrl(x.url)}">${aiEscapeHtml(x.title || 'صفحة')}</a>`).join(' · ') + '</div>';
        }
        if (quota && Number.isFinite(Number(quota.remaining))) {
            html += `<div style="margin-top:6px;font-size:11px;color:#64748b;">المتبقي هذا الشهر: ${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 ? 'إغلاق المساعد الإداري' : 'إظهار المساعد الإداري');
            launcher.title = opening ? 'إغلاق المساعد الإداري' : 'المساعد الإداري';
            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();

            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>انتهت حصة المساعد الشهرية</strong>تتجدد الحصة مع بداية الشهر القادم، أو يمكنك مراجعة خيارات الترقية.<br><a href="subscription.php">مراجعة الباقة</a><div style="margin-top:6px;font-size:11px">لا يزال بإمكانك طلب روابط الصفحات والتنقل بينها دون استهلاك حصة AI.</div></div>`;
            } else {
                chatBody.innerHTML += `<div class="ai-msg ai-msg-bot" style="color:red;">عذراً، تعذر الحصول على إجابة الآن. حاول مرة أخرى لاحقاً.</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;">فشل الاتصال بالخادم.</div>`;
            chatBody.scrollTop = chatBody.scrollHeight;
        }
    }</script>