<?php
session_start();
include 'layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$user_id = $_SESSION['user_id'];

// Function to get system settings
function getSetting($conn, $key) {
    $sql = "SELECT setting_value FROM system_settings WHERE setting_key = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $key);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();
    $stmt->close();
    return $row['setting_value'] ?? '';
}

// Get chatbot settings
$chatbot_enabled = getSetting($conn, 'chatbot_enabled');
$chatbot_name = getSetting($conn, 'chatbot_name') ?: 'Prodigy ENT AI Assistant';
$chatbot_api_key = getSetting($conn, 'chatbot_api_key');

// Get statistics
$stats_sql = "SELECT 
    COUNT(DISTINCT id) as total_conversations,
    COUNT(DISTINCT CASE WHEN DATE(started_at) = CURDATE() THEN id END) as today_conversations,
    COUNT(DISTINCT session_id) as unique_users,
    COALESCE(AVG(TIMESTAMPDIFF(SECOND, started_at, last_activity)), 0) as avg_session_duration
FROM chatbot_conversations";

$stats_result = $conn->query($stats_sql);
$stats = $stats_result ? $stats_result->fetch_assoc() : [
    'total_conversations' => 0,
    'today_conversations' => 0,
    'unique_users' => 0,
    'avg_session_duration' => 0
];

// Get recent conversations
$conversations_sql = "SELECT 
    cc.id,
    cc.session_id,
    cc.user_id,
    cc.user_type,
    cc.status,
    cc.started_at,
    cc.last_activity,
    u.full_name as user_name,
    (SELECT message_text 
     FROM chatbot_messages 
     WHERE conversation_id = cc.id 
     AND sender_type = 'user' 
     ORDER BY created_at DESC 
     LIMIT 1) as last_message
FROM chatbot_conversations cc
LEFT JOIN users u ON cc.user_id = u.user_id
ORDER BY cc.last_activity DESC
LIMIT 20";

$conversations = $conn->query($conversations_sql);
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'AI Chatbot')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        /* Matching patient profile design system */
        .profile-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 2rem;
            border-radius: 12px;
            color: white;
            margin-bottom: 2rem;
        }
        
        .info-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 1.5rem;
        }
        
        .info-card h5 {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 1.25rem;
            padding-bottom: 0.75rem;
            border-bottom: 2px solid #e2e8f0;
        }
        
        .stat-box {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            text-align: center;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #667eea;
            margin-bottom: 0.5rem;
        }
        
        .stat-label {
            color: #64748b;
            font-size: 0.875rem;
            text-transform: uppercase;
            font-weight: 600;
        }
        
        .chat-container {
            display: flex;
            height: calc(100vh - 280px);
            min-height: 600px;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
        }
        
        .chat-sidebar {
            width: 320px;
            background: #f8fafc;
            border-right: 1px solid #e2e8f0;
            display: flex;
            flex-direction: column;
        }
        
        .chat-main {
            flex: 1;
            display: flex;
            flex-direction: column;
            background: white;
        }
        
        .chat-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 1.5rem;
            border-bottom: 1px solid rgba(255,255,255,0.2);
        }
        
        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 1.5rem;
            background: #f8fafc;
        }
        
        .chat-input-area {
            background: white;
            border-top: 1px solid #e2e8f0;
            padding: 1.5rem;
        }
        
        .message {
            display: flex;
            gap: 0.75rem;
            margin-bottom: 1.5rem;
            animation: fadeIn 0.3s ease-in;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .message.user {
            flex-direction: row-reverse;
        }
        
        .message-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.25rem;
            flex-shrink: 0;
        }
        
        .message.bot .message-avatar {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .message.user .message-avatar {
            background: #3b82f6;
            color: white;
        }
        
        .message-bubble {
            max-width: 70%;
            padding: 1rem 1.25rem;
            border-radius: 12px;
            word-wrap: break-word;
            line-height: 1.5;
        }
        
        .message.bot .message-bubble {
            background: white;
            border: 1px solid #e2e8f0;
            color: #1e293b;
            border-bottom-left-radius: 4px;
        }
        
        .message.user .message-bubble {
            background: #3b82f6;
            color: white;
            border-bottom-right-radius: 4px;
        }
        
        .message-meta {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            margin-top: 0.5rem;
            font-size: 0.75rem;
            color: #64748b;
        }
        
        .message.user .message-meta {
            justify-content: flex-end;
            color: rgba(255,255,255,0.8);
        }
        
        .intent-badge {
            display: inline-flex;
            align-items: center;
            padding: 0.25rem 0.75rem;
            border-radius: 12px;
            font-size: 0.7rem;
            font-weight: 600;
            text-transform: uppercase;
        }
        
        .intent-greeting { background: #dbeafe; color: #1e40af; }
        .intent-appointment { background: #dcfce7; color: #166534; }
        .intent-symptoms { background: #fef3c7; color: #92400e; }
        .intent-faq { background: #e0e7ff; color: #4338ca; }
        .intent-emergency { background: #fee2e2; color: #991b1b; }
        .intent-services { background: #ccfbf1; color: #134e4a; }
        .intent-general { background: #f1f5f9; color: #475569; }
        
        .typing-indicator {
            display: inline-flex;
            gap: 0.25rem;
            padding: 0.75rem 1rem;
        }
        
        .typing-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: #94a3b8;
            animation: bounce 1.4s infinite ease-in-out;
        }
        
        .typing-dot:nth-child(1) { animation-delay: -0.32s; }
        .typing-dot:nth-child(2) { animation-delay: -0.16s; }
        
        @keyframes bounce {
            0%, 80%, 100% { transform: scale(0); }
            40% { transform: scale(1); }
        }
        
        .quick-reply {
            display: inline-flex;
            align-items: center;
            padding: 0.5rem 1rem;
            margin: 0.25rem;
            border: 1px solid #e2e8f0;
            border-radius: 20px;
            background: white;
            color: #475569;
            font-size: 0.875rem;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .quick-reply:hover {
            background: #f8fafc;
            border-color: #667eea;
            color: #667eea;
        }
        
        .conversation-item {
            padding: 1rem;
            border-bottom: 1px solid #e2e8f0;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .conversation-item:hover {
            background: white;
        }
        
        .conversation-item.active {
            background: white;
            border-left: 3px solid #667eea;
        }
        
        .status-badge {
            display: inline-block;
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.7rem;
            font-weight: 600;
            text-transform: uppercase;
        }
        
        .status-active { background: #dcfce7; color: #166534; }
        .status-closed { background: #e2e8f0; color: #475569; }
        .status-escalated { background: #fef3c7; color: #92400e; }
        
        .action-btn {
            padding: 0.5rem 1rem;
            border-radius: 6px;
            font-size: 0.875rem;
            border: none;
            cursor: pointer;
            transition: all 0.2s;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            text-decoration: none;
        }
        
        .welcome-screen {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100%;
            text-align: center;
            padding: 2rem;
            color: #64748b;
        }
        
        .welcome-screen i {
            font-size: 4rem;
            color: #667eea;
            margin-bottom: 1rem;
        }
        
        .chat-input {
            display: flex;
            gap: 0.75rem;
        }
        
        .chat-input textarea {
            flex: 1;
            padding: 0.75rem;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            resize: none;
            font-family: inherit;
            font-size: 0.875rem;
        }
        
        .chat-input textarea:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        .medical-alert {
            background: #fef3c7;
            border-left: 4px solid #f59e0b;
            padding: 1rem;
            border-radius: 6px;
            margin-bottom: 1rem;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Page Header -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0"><?php echo htmlspecialchars($chatbot_name); ?></h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item">Communication</li>
                                        <li class="breadcrumb-item active">AI Chatbot</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <?php if ($chatbot_enabled != '1'): ?>
                    <div class="medical-alert">
                        <h6 class="text-warning mb-2"><i class="ri-alert-line me-2"></i>AI Chatbot Disabled</h6>
                        <p class="mb-0">Please enable and configure the chatbot in <a href="system_settings.php" class="fw-bold">System Settings → Chatbot</a></p>
                    </div>
                    <?php endif; ?>

                    <?php if (empty($chatbot_api_key) || $chatbot_api_key == 'your-api-key-here'): ?>
                    <div class="medical-alert">
                        <h6 class="text-warning mb-2"><i class="ri-key-line me-2"></i>API Key Not Configured</h6>
                        <p class="mb-0">Please add your Anthropic API key in <a href="system_settings.php" class="fw-bold">System Settings → Chatbot</a></p>
                    </div>
                    <?php endif; ?>

                    <!-- Stats Overview -->
                    <div class="row mb-4">
                        <div class="col-lg-3 col-md-6">
                            <div class="stat-box">
                                <div class="stat-value"><?php echo number_format($stats['total_conversations']); ?></div>
                                <div class="stat-label">Total Conversations</div>
                            </div>
                        </div>
                        <div class="col-lg-3 col-md-6">
                            <div class="stat-box">
                                <div class="stat-value"><?php echo number_format($stats['today_conversations']); ?></div>
                                <div class="stat-label">Today</div>
                            </div>
                        </div>
                        <div class="col-lg-3 col-md-6">
                            <div class="stat-box">
                                <div class="stat-value"><?php echo number_format($stats['unique_users']); ?></div>
                                <div class="stat-label">Unique Sessions</div>
                            </div>
                        </div>
                        <div class="col-lg-3 col-md-6">
                            <div class="stat-box">
                                <div class="stat-value"><?php echo number_format($stats['avg_session_duration'] / 60, 1); ?>m</div>
                                <div class="stat-label">Avg Duration</div>
                            </div>
                        </div>
                    </div>

                    <!-- Action Buttons -->
                    <div class="info-card">
                        <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
                            <div class="d-flex gap-2 flex-wrap">
                                <button class="action-btn" style="background: #667eea; color: white;" onclick="filterConversations('all')">
                                    <i class="ri-chat-4-line"></i> All
                                </button>
                                <button class="action-btn" style="background: #10b981; color: white;" onclick="filterConversations('active')">
                                    <i class="ri-chat-check-line"></i> Active
                                </button>
                                <button class="action-btn" style="background: #f59e0b; color: white;" onclick="filterConversations('escalated')">
                                    <i class="ri-alarm-warning-line"></i> Escalated
                                </button>
                                <button class="action-btn" style="background: #6b7280; color: white;" onclick="filterConversations('closed')">
                                    <i class="ri-chat-off-line"></i> Closed
                                </button>
                            </div>
                            <a href="system_settings.php" class="action-btn" style="background: #3b82f6; color: white;">
                                <i class="ri-settings-3-line"></i> Settings
                            </a>
                        </div>
                    </div>

                    <!-- Chat Interface -->
                    <div class="chat-container">
                        
                        <!-- Sidebar with Conversations -->
                        <div class="chat-sidebar">
                            <div class="p-3 bg-white border-bottom">
                                <div class="d-flex justify-content-between align-items-center">
                                    <h6 class="mb-0 fw-bold">Conversations</h6>
                                    <button class="btn btn-sm" style="background: #667eea; color: white;" onclick="startNewChat()">
                                        <i class="ri-add-line"></i> New
                                    </button>
                                </div>
                            </div>
                            
                            <div style="flex: 1; overflow-y: auto;">
                                <?php if ($conversations && $conversations->num_rows > 0): ?>
                                    <?php while($conv = $conversations->fetch_assoc()): ?>
                                    <div class="conversation-item" data-id="<?php echo $conv['id']; ?>" onclick="loadConversation(<?php echo $conv['id']; ?>)">
                                        <div class="d-flex justify-content-between align-items-start mb-2">
                                            <div class="fw-bold small"><?php echo htmlspecialchars($conv['user_name'] ?: 'Guest User'); ?></div>
                                            <span class="status-badge status-<?php echo $conv['status']; ?>">
                                                <?php echo $conv['status']; ?>
                                            </span>
                                        </div>
                                        <div class="text-muted small mb-2" style="font-size: 0.8rem; line-height: 1.4;">
                                            <?php echo $conv['last_message'] ? htmlspecialchars(substr($conv['last_message'], 0, 60)) . '...' : 'No messages'; ?>
                                        </div>
                                        <div class="d-flex justify-content-between align-items-center">
                                            <span class="text-muted" style="font-size: 0.7rem;">
                                                <?php echo date('M j, g:i A', strtotime($conv['last_activity'])); ?>
                                            </span>
                                            <span class="badge" style="background: #f1f5f9; color: #64748b; font-size: 0.65rem;">
                                                <?php echo strtoupper($conv['user_type']); ?>
                                            </span>
                                        </div>
                                    </div>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <div class="text-center p-4">
                                        <i class="ri-chat-off-line fs-2 text-muted mb-2 d-block"></i>
                                        <p class="small text-muted mb-0">No conversations yet</p>
                                        <button class="btn btn-sm btn-outline-primary mt-2" onclick="startNewChat()">
                                            Start First Chat
                                        </button>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Main Chat Area -->
                        <div class="chat-main">
                            
                            <!-- Chat Header -->
                            <div class="chat-header">
                                <div class="d-flex align-items-center justify-content-between">
                                    <div class="d-flex align-items-center gap-3">
                                        <div style="width: 50px; height: 50px; background: white; border-radius: 50%; display: flex; align-items: center; justify-content: center;">
                                            <i class="ri-robot-line" style="font-size: 1.75rem; color: #667eea;"></i>
                                        </div>
                                        <div>
                                            <h5 class="mb-1"><?php echo htmlspecialchars($chatbot_name); ?></h5>
                                            <small class="opacity-75">Powered by Claude Sonnet 4</small>
                                        </div>
                                    </div>
                                    <div class="d-flex gap-2">
                                        <button class="btn btn-light btn-sm" onclick="exportChat()" title="Export Chat">
                                            <i class="ri-download-line"></i>
                                        </button>
                                        <button class="btn btn-light btn-sm" onclick="clearChat()" title="Clear Chat">
                                            <i class="ri-refresh-line"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>

                            <!-- Messages Area -->
                            <div class="chat-messages" id="chatMessages">
                                <div class="welcome-screen">
                                    <i class="ri-robot-line"></i>
                                    <h4 class="mb-3">Welcome to <?php echo htmlspecialchars($chatbot_name); ?></h4>
                                    <p class="mb-4">I'm here to help you with appointments, answer questions about ENT services, and provide general information. How can I assist you today?</p>
                                    <div class="d-flex flex-wrap gap-2 justify-content-center">
                                        <button class="quick-reply" onclick="sendQuick('I need to book an appointment')">
                                            📅 Book Appointment
                                        </button>
                                        <button class="quick-reply" onclick="sendQuick('What are your visiting hours?')">
                                            🕐 Visiting Hours
                                        </button>
                                        <button class="quick-reply" onclick="sendQuick('I have ear pain')">
                                            👂 ENT Symptoms
                                        </button>
                                        <button class="quick-reply" onclick="sendQuick('What services do you offer?')">
                                            🏥 Our Services
                                        </button>
                                    </div>
                                </div>
                            </div>

                            <!-- Input Area -->
                            <div class="chat-input-area">
                                <div class="mb-3" id="quickReplies" style="display: none;">
                                    <!-- Dynamic quick replies will appear here -->
                                </div>
                                <div class="chat-input">
                                    <textarea 
                                        id="messageInput" 
                                        rows="2" 
                                        placeholder="Type your message here..."
                                        onkeydown="handleKeyPress(event)"></textarea>
                                    <button class="btn" style="background: #667eea; color: white; padding: 0 1.5rem;" onclick="sendMessage()">
                                        <i class="ri-send-plane-fill"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>

    <script>
        let currentConversationId = null;
        let sessionId = 'session_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
        let messageHistory = [];
        
        // Handle Enter key
        function handleKeyPress(event) {
            if (event.key === 'Enter' && !event.shiftKey) {
                event.preventDefault();
                sendMessage();
            }
        }
        
        // Send quick reply
        function sendQuick(message) {
            $('#messageInput').val(message);
            sendMessage();
        }
        
        // Start new chat
        function startNewChat() {
            currentConversationId = null;
            sessionId = 'session_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
            messageHistory = [];
            
            $('#chatMessages').html(`
                <div class="welcome-screen">
                    <i class="ri-robot-line"></i>
                    <h4 class="mb-3">Welcome to <?php echo htmlspecialchars($chatbot_name); ?></h4>
                    <p class="mb-4">I'm here to help you with appointments, answer questions about ENT services, and provide general information. How can I assist you today?</p>
                    <div class="d-flex flex-wrap gap-2 justify-content-center">
                        <button class="quick-reply" onclick="sendQuick('I need to book an appointment')">📅 Book Appointment</button>
                        <button class="quick-reply" onclick="sendQuick('What are your visiting hours?')">🕐 Visiting Hours</button>
                        <button class="quick-reply" onclick="sendQuick('I have ear pain')">👂 ENT Symptoms</button>
                        <button class="quick-reply" onclick="sendQuick('What services do you offer?')">🏥 Our Services</button>
                    </div>
                </div>
            `);
            
            $('.conversation-item').removeClass('active');
        }
        
        // Send message
        function sendMessage() {
            const input = $('#messageInput');
            const message = input.val().trim();
            
            if (!message) return;
            
            input.val('');
            addMessage(message, 'user');
            showTyping();
            
            $.ajax({
                url: 'ajax/ai_assistant.php',
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    action: 'chatbot_response',
                    data: {
                        message: message,
                        session_id: sessionId,
                        conversation_id: currentConversationId,
                        message_history: messageHistory
                    }
                }),
                success: function(response) {
                    hideTyping();
                    
                    if (response.success) {
                        if (response.conversation_id) {
                            currentConversationId = response.conversation_id;
                        }
                        
                        addMessage(response.response, 'bot', response.intent, response.confidence_score);
                        
                        messageHistory.push(
                            { sender_type: 'user', message_text: message },
                            { sender_type: 'bot', message_text: response.response, intent: response.intent }
                        );
                        
                        if (response.action_required) {
                            handleAction(response.action_required);
                        }
                        
                        // Reload conversation list
                        setTimeout(() => location.reload(), 3000);
                    } else {
                        addMessage(response.message || 'Sorry, I encountered an error. Please try again.', 'bot');
                    }
                },
                error: function(xhr) {
                    hideTyping();
                    console.error('Error:', xhr.responseText);
                    addMessage('Sorry, I could not connect. Please check your settings.', 'bot');
                }
            });
        }
        
        // Add message to chat
        function addMessage(text, type, intent = null, confidence = null) {
            const messagesDiv = $('#chatMessages');
            messagesDiv.find('.welcome-screen').remove();
            
            const messageHtml = `
                <div class="message ${type}">
                    <div class="message-avatar">
                        ${type === 'bot' ? '🤖' : '👤'}
                    </div>
                    <div style="flex: 1;">
                        <div class="message-bubble">
                            ${escapeHtml(text)}
                        </div>
                        <div class="message-meta">
                            <span>${new Date().toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' })}</span>
                            ${intent ? `<span class="intent-badge intent-${intent}">${intent}</span>` : ''}
                            ${confidence ? `<span style="opacity: 0.7;">Confidence: ${Math.round(confidence * 100)}%</span>` : ''}
                        </div>
                    </div>
                </div>
            `;
            
            messagesDiv.append(messageHtml);
            messagesDiv.scrollTop(messagesDiv[0].scrollHeight);
        }
        
        // Show typing indicator
        function showTyping() {
            const typingHtml = `
                <div class="message bot" id="typingIndicator">
                    <div class="message-avatar">🤖</div>
                    <div class="message-bubble">
                        <div class="typing-indicator">
                            <div class="typing-dot"></div>
                            <div class="typing-dot"></div>
                            <div class="typing-dot"></div>
                        </div>
                    </div>
                </div>
            `;
            $('#chatMessages').append(typingHtml);
            $('#chatMessages').scrollTop($('#chatMessages')[0].scrollHeight);
        }
        
        // Hide typing indicator
        function hideTyping() {
            $('#typingIndicator').remove();
        }
        
        // Load conversation
        function loadConversation(id) {
            currentConversationId = id;
            
            $('.conversation-item').removeClass('active');
            $(`.conversation-item[data-id="${id}"]`).addClass('active');
            
            $.ajax({
                url: 'api/load_conversation.php?id=' + id,
                method: 'GET',
                success: function(response) {
                    if (response.success) {
                        $('#chatMessages').empty();
                        sessionId = response.conversation.session_id;
                        messageHistory = [];
                        
                        response.messages.forEach(msg => {
                            addMessage(msg.message_text, msg.sender_type, msg.intent, msg.confidence_score);
                            messageHistory.push({
                                sender_type: msg.sender_type,
                                message_text: msg.message_text,
                                intent: msg.intent
                            });
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: 'Failed to load conversation',
                            confirmButtonColor: '#667eea'
                        });
                    }
                },
                error: function() {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Failed to load conversation',
                        confirmButtonColor: '#667eea'
                    });
                }
            });
        }
        
        // Handle actions
        function handleAction(action) {
            switch(action) {
                case 'book_appointment':
                    Swal.fire({
                        title: 'Book Appointment',
                        text: 'Would you like to book an appointment now?',
                        icon: 'question',
                        showCancelButton: true,
                        confirmButtonText: 'Yes, book now',
                        confirmButtonColor: '#667eea',
                        cancelButtonColor: '#6b7280'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            window.location.href = 'book_appointment.php';
                        }
                    });
                    break;
                case 'escalate_to_human':
                    addMessage('Connecting you to a human agent...', 'bot');
                    Swal.fire({
                        title: 'Human Agent Support',
                        text: 'An agent will respond to you shortly.',
                        icon: 'info',
                        confirmButtonColor: '#667eea'
                    });
                    break;
                case 'show_emergency_contact':
                    Swal.fire({
                        title: 'Emergency Contact',
                        html: '<p class="mb-3">For urgent medical assistance, please call:</p><h2 class="text-danger mb-3">+254-700-000-111</h2><p class="small text-muted">Available 24/7 for emergencies</p>',
                        icon: 'warning',
                        confirmButtonColor: '#dc2626'
                    });
                    break;
            }
        }
        
        // Filter conversations
        function filterConversations(filter) {
            window.location.href = 'chatbot.php?filter=' + filter;
        }
        
        // Export chat
        function exportChat() {
            if (!currentConversationId) {
                Swal.fire({
                    icon: 'info',
                    title: 'No Conversation Selected',
                    text: 'Please select a conversation to export',
                    confirmButtonColor: '#667eea'
                });
                return;
            }
            
            Swal.fire({
                title: 'Export Chat',
                text: 'Choose export format',
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Export as PDF',
                cancelButtonText: 'Export as Text',
                confirmButtonColor: '#667eea',
                cancelButtonColor: '#6b7280'
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = `api/export_conversation.php?id=${currentConversationId}&format=pdf`;
                } else if (result.dismiss === Swal.DismissReason.cancel) {
                    window.location.href = `api/export_conversation.php?id=${currentConversationId}&format=txt`;
                }
            });
        }
        
        // Clear chat
        function clearChat() {
            Swal.fire({
                title: 'Clear Chat?',
                text: 'This will start a new conversation',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes, clear it',
                confirmButtonColor: '#667eea',
                cancelButtonColor: '#6b7280'
            }).then((result) => {
                if (result.isConfirmed) {
                    startNewChat();
                }
            });
        }
        
        // Escape HTML
        function escapeHtml(text) {
            const map = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            };
            return text.replace(/[&<>"']/g, m => map[m]);
        }
        
        // Auto-scroll on load
        $(document).ready(function() {
            const messagesDiv = $('#chatMessages');
            if (messagesDiv.length) {
                messagesDiv.scrollTop(messagesDiv[0].scrollHeight);
            }
            
            // Auto-focus input
            $('#messageInput').focus();
        });
    </script>
</body>
</html>