Sindbad~EG File Manager

Current Path : /home/copmadinaarea/thecopmadinaarea.org/portal/includes/
Upload File :
Current File : /home/copmadinaarea/thecopmadinaarea.org/portal/includes/chat-hub-widget.php

<?php
// Check if AI chatbot is enabled
$aiChatbotEnabled = false;
$chatWelcomeMessage = 'Need help? Chat with us!';
try {
    require_once __DIR__ . '/../classes/ChatbotService.php';
    $chatbotService = new ChatbotService();
    $aiChatbotEnabled = $chatbotService->isEnabled();
    $chatbotSettings = $chatbotService->getAllSettings();
    $chatWelcomeMessage = $chatbotSettings['chat_welcome_message'] ?? 'Need help? Chat with us!';
} catch (Exception $e) {
    $aiChatbotEnabled = false;
}
?>

<!-- Chat Hub Widget - Choose between Admin Chat or AI Chatbot -->
<style>
#chat-hub-widget {
    position: fixed;
    bottom: 20px;
    right: 20px;
    z-index: 9999;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

#chat-hub-button {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    background: linear-gradient(135deg, #1E40AF 0%, #9333EA 50%, #F97316 100%);
    color: white;
    border: none;
    cursor: pointer;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28px;
    transition: all 0.3s ease;
    position: relative;
}

#chat-hub-button:hover {
    transform: scale(1.1);
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.25);
}

#chat-hub-button.pulse {
    animation: pulse 2s infinite;
}

#chat-hub-button.bounce {
    animation: bounce 0.6s ease;
}

@keyframes pulse {
    0% {
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15), 0 0 0 0 rgba(147, 51, 234, 0.7);
    }
    50% {
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15), 0 0 0 10px rgba(147, 51, 234, 0);
    }
    100% {
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15), 0 0 0 0 rgba(147, 51, 234, 0);
    }
}

@keyframes bounce {
    0%, 100% {
        transform: translateY(0);
    }
    25% {
        transform: translateY(-10px);
    }
    50% {
        transform: translateY(0);
    }
    75% {
        transform: translateY(-5px);
    }
}

/* Welcome Notification Badge */
.chat-notification-badge {
    position: absolute;
    top: -5px;
    right: -5px;
    background: linear-gradient(135deg, #EF4444 0%, #DC2626 100%);
    color: white;
    width: 24px;
    height: 24px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    font-weight: bold;
    border: 2px solid white;
    animation: scaleIn 0.3s ease;
}

@keyframes scaleIn {
    from {
        transform: scale(0);
    }
    to {
        transform: scale(1);
    }
}

/* Welcome Message Bubble */
#welcome-bubble {
    position: absolute;
    bottom: 80px;
    right: 0;
    background: white;
    border-radius: 16px;
    box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
    padding: 16px 20px;
    max-width: 350px;
    width: 350px;
    display: none;
    animation: slideInRight 0.5s ease;
}

#welcome-bubble.show {
    display: block;
}

#welcome-bubble::after {
    content: '';
    position: absolute;
    bottom: -8px;
    right: 20px;
    width: 0;
    height: 0;
    border-left: 10px solid transparent;
    border-right: 10px solid transparent;
    border-top: 10px solid white;
}

@keyframes slideInRight {
    from {
        opacity: 0;
        transform: translateX(20px);
    }
    to {
        opacity: 1;
        transform: translateX(0);
    }
}

.welcome-bubble-close {
    position: absolute;
    top: 8px;
    right: 8px;
    background: none;
    border: none;
    color: #9ca3af;
    cursor: pointer;
    font-size: 18px;
    width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: all 0.2s;
}

.welcome-bubble-close:hover {
    background: #f3f4f6;
    color: #1f2937;
}

#chat-hub-menu {
    position: absolute;
    bottom: 80px;
    right: 0;
    background: white;
    border-radius: 16px;
    box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
    padding: 8px;
    display: none;
    min-width: 250px;
}

#chat-hub-menu.open {
    display: block;
    animation: slideUp 0.3s ease;
}

@keyframes slideUp {
    from {
        opacity: 0;
        transform: translateY(10px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.chat-option {
    display: flex;
    align-items: center;
    padding: 12px 16px;
    margin: 4px 0;
    border-radius: 12px;
    cursor: pointer;
    transition: all 0.2s;
    border: 2px solid transparent;
}

.chat-option:hover {
    background: linear-gradient(135deg, rgba(30, 64, 175, 0.1) 0%, rgba(147, 51, 234, 0.1) 100%);
    border-color: #9333EA;
}

.chat-option-icon {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 12px;
    font-size: 20px;
}

.chat-option-content h4 {
    margin: 0;
    font-size: 14px;
    font-weight: 600;
    color: #1f2937;
}

.chat-option-content p {
    margin: 2px 0 0 0;
    font-size: 12px;
    color: #6b7280;
}

/* Admin Chat Window */
#admin-chat-window {
    display: none;
    position: fixed;
    bottom: 100px;
    right: 20px;
    width: 380px;
    max-width: calc(100vw - 40px);
    background: white;
    border-radius: 16px;
    box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
    z-index: 9998;
}

#admin-chat-window.open {
    display: flex;
    flex-direction: column;
    animation: slideUp 0.3s ease;
}

/* AI Chatbot Window */
#ai-chatbot-window {
    display: none;
    position: fixed;
    bottom: 100px;
    right: 20px;
    width: 380px;
    max-width: calc(100vw - 40px);
    height: 550px;
    max-height: 80vh;
    background: white;
    border-radius: 16px;
    box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
    z-index: 9998;
}

#ai-chatbot-window.open {
    display: flex;
    flex-direction: column;
    animation: slideUp 0.3s ease;
}

.chat-header {
    background: linear-gradient(135deg, #1E40AF 0%, #9333EA 100%);
    color: white;
    padding: 16px 20px;
    border-radius: 16px 16px 0 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.chat-header h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
}

.chat-close {
    background: none;
    border: none;
    color: white;
    font-size: 24px;
    cursor: pointer;
    padding: 0;
    width: 30px;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: background 0.2s;
}

.chat-close:hover {
    background: rgba(255, 255, 255, 0.2);
}

.chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 16px;
    background: #f9fafb;
}

.chat-input-area {
    padding: 12px;
    background: white;
    border-top: 1px solid #e5e7eb;
    border-radius: 0 0 16px 16px;
}

.chat-input-form {
    display: flex;
    gap: 8px;
}

.chat-input {
    flex: 1;
    padding: 10px 14px;
    border: 1px solid #d1d5db;
    border-radius: 20px;
    font-size: 14px;
    outline: none;
}

.chat-input:focus {
    border-color: #9333EA;
}

.chat-send-btn {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: linear-gradient(135deg, #1E40AF 0%, #9333EA 100%);
    color: white;
    border: none;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
}

.chat-send-btn:hover {
    transform: scale(1.1);
}

@media (max-width: 768px) {
    #admin-chat-window, #ai-chatbot-window {
        width: calc(100% - 40px);
        right: 20px;
        left: 20px;
    }
    
    #welcome-bubble {
        max-width: calc(100vw - 90px);
        width: calc(100vw - 90px);
        right: 0;
    }
    
    #chat-hub-menu {
        right: -10px;
    }
}

@media (max-width: 480px) {
    #welcome-bubble {
        max-width: calc(100vw - 80px);
        width: calc(100vw - 80px);
    }
}
</style>

<div id="chat-hub-widget">
    <!-- Welcome Message Bubble -->
    <div id="welcome-bubble">
        <button class="welcome-bubble-close" onclick="closeWelcomeBubble()" aria-label="Close">
            <i class="fas fa-times"></i>
        </button>
        <div style="display: flex; align-items: start; gap: 12px;">
            <div style="width: 44px; height: 44px; border-radius: 50%; background: linear-gradient(135deg, #1E40AF 0%, #9333EA 100%); display: flex; align-items: center; justify-content: center; color: white; font-size: 22px; flex-shrink: 0;">
                💬
            </div>
            <div style="flex: 1;">
                <h4 style="margin: 0 0 6px 0; font-size: 15px; font-weight: 600; color: #1f2937;">
                    <?php echo htmlspecialchars($chatWelcomeMessage); ?>
                </h4>
            </div>
        </div>
        <button onclick="openChatFromWelcome()" style="width: 100%; padding: 8px 12px; background: linear-gradient(135deg, #1E40AF 0%, #9333EA 100%); color: white; border: none; border-radius: 8px; font-size: 13px; font-weight: 600; cursor: pointer; margin-top: 8px;">
            Start Chatting
        </button>
    </div>

    <!-- Main Chat Button -->
    <button id="chat-hub-button" onclick="toggleChatHub()" aria-label="Open chat options">
        <i class="fas fa-comments"></i>
        <span id="notification-badge" class="chat-notification-badge" style="display: none;">1</span>
    </button>

    <!-- Chat Options Menu -->
    <div id="chat-hub-menu">
        <div class="chat-option" onclick="openAdminChat()">
            <div class="chat-option-icon" style="background: linear-gradient(135deg, #10B981 0%, #059669 100%); color: white;">
                <i class="fas fa-user-headset"></i>
            </div>
            <div class="chat-option-content">
                <h4>Chat with Admin</h4>
                <p>Get help from our team</p>
            </div>
        </div>

        <?php if ($aiChatbotEnabled): ?>
        <div class="chat-option" onclick="openAIChatbot()">
            <div class="chat-option-icon" style="background: linear-gradient(135deg, #3B82F6 0%, #9333EA 100%); color: white;">
                <i class="fas fa-robot"></i>
            </div>
            <div class="chat-option-content">
                <h4>AI Assistant</h4>
                <p>Instant answers 24/7</p>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <!-- Admin Chat Window -->
    <div id="admin-chat-window">
        <div class="chat-header">
            <h3><i class="fas fa-user-headset mr-2"></i>Chat with Admin</h3>
            <button class="chat-close" onclick="closeAdminChat()">&times;</button>
        </div>
        <div id="admin-chat-messages" class="chat-messages" style="max-height: 300px;"></div>
        <div class="chat-input-area">
            <form id="admin-chat-form" class="chat-input-form">
                <textarea id="admin-chat-input" class="chat-input" rows="2" placeholder="Type your message..." style="resize: none;"></textarea>
                <button type="submit" class="chat-send-btn">
                    <i class="fas fa-paper-plane"></i>
                </button>
            </form>
        </div>
    </div>

    <!-- AI Chatbot Window -->
    <?php if ($aiChatbotEnabled): ?>
    <div id="ai-chatbot-window">
        <div class="chat-header">
            <h3><i class="fas fa-robot mr-2"></i><?php echo htmlspecialchars($chatbotSettings['bot_name'] ?? 'AI Assistant'); ?></h3>
            <button class="chat-close" onclick="closeAIChatbot()">&times;</button>
        </div>
        <div id="ai-chat-messages" class="chat-messages">
            <div class="mb-3 flex items-start gap-2">
                <div style="width: 36px; height: 36px; border-radius: 50%; background: linear-gradient(135deg, #1E40AF 0%, #9333EA 100%); display: flex; align-items: center; justify-content: center; color: white; font-size: 18px;">
                    <?php echo $chatbotSettings['bot_avatar'] ?? '🤖'; ?>
                </div>
                <div style="max-width: 70%; padding: 12px 16px; background: white; border-radius: 16px; border-bottom-left-radius: 4px; box-shadow: 0 1px 2px rgba(0,0,0,0.1);">
                    <?php echo htmlspecialchars($chatbotSettings['welcome_message'] ?? 'Hello! How can I help you?'); ?>
                </div>
            </div>
        </div>
        <div class="chat-input-area">
            <form id="ai-chat-form" class="chat-input-form">
                <input type="text" id="ai-chat-input" class="chat-input" placeholder="<?php echo htmlspecialchars($chatbotSettings['placeholder_text'] ?? 'Type your message...'); ?>" autocomplete="off">
                <button type="submit" class="chat-send-btn">
                    <i class="fas fa-paper-plane"></i>
                </button>
            </form>
        </div>
    </div>
    <?php endif; ?>
</div>

<script>
// Chat Hub State
let chatHubOpen = false;
let adminChatOpen = false;
let aiChatOpen = false;
let adminChatConversationId = null;
let aiChatSessionId = 'chatbot_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
let aiChatConversationId = null;

// Toggle Chat Hub Menu
function toggleChatHub() {
    chatHubOpen = !chatHubOpen;
    const menu = document.getElementById('chat-hub-menu');
    
    if (chatHubOpen) {
        menu.classList.add('open');
        // Close any open chat windows
        closeAdminChat();
        closeAIChatbot();
    } else {
        menu.classList.remove('open');
    }
}

// Open Admin Chat
function openAdminChat() {
    document.getElementById('chat-hub-menu').classList.remove('open');
    document.getElementById('admin-chat-window').classList.add('open');
    adminChatOpen = true;
    chatHubOpen = false;
    
    if (!adminChatConversationId) {
        initAdminChat();
    }
}

// Close Admin Chat
function closeAdminChat() {
    document.getElementById('admin-chat-window').classList.remove('open');
    adminChatOpen = false;
}

// Open AI Chatbot
function openAIChatbot() {
    document.getElementById('chat-hub-menu').classList.remove('open');
    document.getElementById('ai-chatbot-window').classList.add('open');
    aiChatOpen = true;
    chatHubOpen = false;
    
    if (!aiChatConversationId) {
        loadAIHistory();
    }
}

// Close AI Chatbot
function closeAIChatbot() {
    document.getElementById('ai-chatbot-window').classList.remove('open');
    aiChatOpen = false;
}

// Admin Chat Functions
async function initAdminChat() {
    try {
        const res = await fetch('<?php echo BASE_URL; ?>api/chat_start.php');
        const data = await res.json();
        if (data.success) {
            adminChatConversationId = data.conversation_id;
            fetchAdminMessages();
        }
    } catch (e) {
        console.error('Admin chat init failed', e);
    }
}

async function sendAdminMessage(message) {
    if (!message || !adminChatConversationId) return;
    
    const formData = new FormData();
    formData.append('conversation_id', adminChatConversationId);
    formData.append('message', message);
    
    try {
        const res = await fetch('<?php echo BASE_URL; ?>api/chat_send.php', {
            method: 'POST',
            body: formData
        });
        const data = await res.json();
        if (data.success) {
            fetchAdminMessages();
        }
    } catch (e) {
        console.error('Admin chat send failed', e);
    }
}

async function fetchAdminMessages() {
    if (!adminChatConversationId) return;
    
    try {
        const params = new URLSearchParams();
        params.append('conversation_id', adminChatConversationId);
        
        const res = await fetch('<?php echo BASE_URL; ?>api/chat_fetch.php?' + params.toString());
        const data = await res.json();
        if (!data.success) return;
        
        const container = document.getElementById('admin-chat-messages');
        container.innerHTML = '';
        
        (data.messages || []).forEach(msg => {
            const isAdmin = msg.sender_type === 'admin';
            const div = document.createElement('div');
            div.className = 'mb-3 flex ' + (isAdmin ? 'justify-start' : 'justify-end');
            div.innerHTML = `
                <div style="max-width: 70%; padding: 10px 14px; border-radius: 16px; ${isAdmin ? 'background: white; color: #1f2937;' : 'background: linear-gradient(135deg, #1E40AF 0%, #9333EA 100%); color: white;'}">
                    ${escapeHtml(msg.message_text || '')}
                </div>
            `;
            container.appendChild(div);
        });
        
        container.scrollTop = container.scrollHeight;
    } catch (e) {
        console.error('Admin chat fetch failed', e);
    }
}

// AI Chatbot Functions
async function loadAIHistory() {
    try {
        const res = await fetch('<?php echo BASE_URL; ?>api/chatbot.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                action: 'get_history',
                session_id: aiChatSessionId
            })
        });
        const data = await res.json();
        if (data.success && data.history.length > 1) {
            const container = document.getElementById('ai-chat-messages');
            container.innerHTML = '';
            data.history.forEach(msg => {
                addAIMessage(msg.message, msg.message_type, false);
            });
        }
    } catch (e) {
        console.error('AI chat history load failed', e);
    }
}

async function sendAIMessage(message) {
    if (!message) return;
    
    addAIMessage(message, 'user');
    
    try {
        const res = await fetch('<?php echo BASE_URL; ?>api/chatbot.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                action: 'send_message',
                message: message,
                session_id: aiChatSessionId
            })
        });
        const data = await res.json();
        if (data.success) {
            aiChatConversationId = data.conversation_id;
            addAIMessage(data.response, 'bot');
        }
    } catch (e) {
        console.error('AI chat send failed', e);
        addAIMessage('Sorry, I encountered an error. Please try again.', 'bot');
    }
}

function addAIMessage(text, type, scroll = true) {
    const container = document.getElementById('ai-chat-messages');
    const div = document.createElement('div');
    div.className = 'mb-3 flex ' + (type === 'bot' ? 'items-start gap-2' : 'justify-end');
    
    if (type === 'bot') {
        div.innerHTML = `
            <div style="width: 36px; height: 36px; border-radius: 50%; background: linear-gradient(135deg, #1E40AF 0%, #9333EA 100%); display: flex; align-items: center; justify-content: center; color: white; font-size: 18px; flex-shrink: 0;">
                <?php echo $chatbotSettings['bot_avatar'] ?? '🤖'; ?>
            </div>
            <div style="max-width: 70%; padding: 12px 16px; background: white; border-radius: 16px; border-bottom-left-radius: 4px; box-shadow: 0 1px 2px rgba(0,0,0,0.1); color: #1f2937;">
                ${escapeHtml(text)}
            </div>
        `;
    } else {
        div.innerHTML = `
            <div style="max-width: 70%; padding: 12px 16px; background: linear-gradient(135deg, #1E40AF 0%, #9333EA 100%); color: white; border-radius: 16px; border-bottom-right-radius: 4px;">
                ${escapeHtml(text)}
            </div>
        `;
    }
    
    container.appendChild(div);
    if (scroll) container.scrollTop = container.scrollHeight;
}

// Form Handlers
document.getElementById('admin-chat-form')?.addEventListener('submit', (e) => {
    e.preventDefault();
    const input = document.getElementById('admin-chat-input');
    const message = input.value.trim();
    if (message) {
        sendAdminMessage(message);
        input.value = '';
    }
});

document.getElementById('ai-chat-form')?.addEventListener('submit', (e) => {
    e.preventDefault();
    const input = document.getElementById('ai-chat-input');
    const message = input.value.trim();
    if (message) {
        sendAIMessage(message);
        input.value = '';
    }
});

// Utility
function escapeHtml(text) {
    const map = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
    };
    return String(text).replace(/[&<>"']/g, m => map[m]);
}

// Poll for new admin messages
setInterval(() => {
    if (adminChatOpen && adminChatConversationId) {
        fetchAdminMessages();
    }
}, 4000);

// Close menu when clicking outside
document.addEventListener('click', (e) => {
    const widget = document.getElementById('chat-hub-widget');
    if (!widget.contains(e.target) && chatHubOpen) {
        toggleChatHub();
    }
});

// Welcome Bubble Functions
function closeWelcomeBubble() {
    const bubble = document.getElementById('welcome-bubble');
    const badge = document.getElementById('notification-badge');
    const button = document.getElementById('chat-hub-button');
    
    bubble.classList.remove('show');
    badge.style.display = 'none';
    button.classList.remove('pulse');
    
    // Remember user dismissed the welcome
    localStorage.setItem('chat_welcome_dismissed', 'true');
}

function openChatFromWelcome() {
    closeWelcomeBubble();
    toggleChatHub();
}

// Auto-popup welcome animation
function showWelcomeAnimation() {
    // Check if user has dismissed before
    const dismissed = localStorage.getItem('chat_welcome_dismissed');
    if (dismissed) return;
    
    // Check if user has used the chat before
    const hasUsedChat = localStorage.getItem('chat_used');
    if (hasUsedChat) return;
    
    const bubble = document.getElementById('welcome-bubble');
    const badge = document.getElementById('notification-badge');
    const button = document.getElementById('chat-hub-button');
    
    // Wait 3 seconds after page load
    setTimeout(() => {
        // Bounce animation on button
        button.classList.add('bounce');
        setTimeout(() => button.classList.remove('bounce'), 600);
        
        // Show notification badge
        badge.style.display = 'flex';
        
        // Add pulse animation
        button.classList.add('pulse');
    }, 3000);
    
    // Show welcome bubble after 5 seconds
    setTimeout(() => {
        bubble.classList.add('show');
        
        // Auto-hide after 15 seconds if not interacted with
        setTimeout(() => {
            if (bubble.classList.contains('show')) {
                closeWelcomeBubble();
            }
        }, 15000);
    }, 5000);
}

// Initialize welcome animation on page load
document.addEventListener('DOMContentLoaded', () => {
    showWelcomeAnimation();
});

// Mark chat as used when user opens any chat
const originalOpenAdminChat = openAdminChat;
openAdminChat = function() {
    localStorage.setItem('chat_used', 'true');
    closeWelcomeBubble();
    originalOpenAdminChat();
};

const originalOpenAIChatbot = openAIChatbot;
openAIChatbot = function() {
    localStorage.setItem('chat_used', 'true');
    closeWelcomeBubble();
    originalOpenAIChatbot();
};
</script>

Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists