<?php
/**
 * ============================================================================
 * ai-assistant/index.php - Enhanced AIM AI Assistant Interface (FIXED)
 * ============================================================================
 * Features: Chat, History, Behavior Settings, Learning, Typing Animation
 */

// Security check
define('AIMS_ACCESS', true);

// Load configuration
require_once __DIR__ . '/../config/config.php';

// Check authentication
if (!isLoggedIn()) {
    redirect('/auth/login.php', 'Please login to access AIM AI', 'warning');
}

// Get user details
$userId = getUserId();
$userName = getUserName();
$userType = getUserType();

// Page title
$pageTitle = 'AIM AI Assistant';

// Include header
include __DIR__ . '/../includes/meta.php';
include __DIR__ . '/../includes/header.php';
?>

<div class="container-fluid py-4">
    <div class="row">
        <div class="col-lg-10 col-xl-9 mx-auto">
            <!-- AI Assistant Header -->
            <div class="card border-0 shadow-sm mb-4" style="background: linear-gradient(135deg, #059669 0%, #047857 100%);">
                <div class="card-body text-white p-4">
                    <div class="row align-items-center">
                        <div class="col-auto">
                            <div class="bg-white rounded-circle p-3" style="width: 70px; height: 70px; display: flex; align-items: center; justify-content: center;">
                                <i class="bi bi-robot text-success" style="font-size: 2rem;"></i>
                            </div>
                        </div>
                        <div class="col">
                            <h2 class="mb-1 fw-bold">AIM AI Assistant</h2>
                            <p class="mb-0 opacity-75">
                                Your intelligent farming companion - Bilingual support (English & Lusoga)
                            </p>
                        </div>
                        <div class="col-auto">
                            <button class="btn btn-light btn-sm" onclick="loadStats()">
                                <i class="bi bi-graph-up me-1"></i> Stats
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Navigation Tabs -->
            <ul class="nav nav-tabs nav-fill mb-4" id="aiTabs" role="tablist">
                <li class="nav-item" role="presentation">
                    <button class="nav-link active" id="chat-tab" data-bs-toggle="tab" data-bs-target="#chat" type="button">
                        <i class="bi bi-chat-dots me-2"></i>Chat
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="history-tab" data-bs-toggle="tab" data-bs-target="#history" type="button">
                        <i class="bi bi-clock-history me-2"></i>History
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="behavior-tab" data-bs-toggle="tab" data-bs-target="#behavior" type="button">
                        <i class="bi bi-sliders me-2"></i>Behavior
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="learning-tab" data-bs-toggle="tab" data-bs-target="#learning" type="button">
                        <i class="bi bi-lightbulb me-2"></i>Learning
                    </button>
                </li>
            </ul>

            <!-- Tab Content -->
            <div class="tab-content" id="aiTabContent">
                <!-- CHAT TAB -->
                <div class="tab-pane fade show active" id="chat" role="tabpanel">
                    <!-- Quick Questions -->
                    <div class="card border-0 shadow-sm mb-3">
                        <div class="card-body">
                            <h6 class="text-muted mb-3">
                                <i class="bi bi-lightning-charge me-2"></i>Quick Questions
                            </h6>
                            <div class="row g-2" id="quickQuestions">
                                <div class="col-md-4">
                                    <button class="btn btn-outline-success btn-sm w-100 text-start quick-question" 
                                            data-question="What are the signs of maize rust disease?">
                                        <i class="bi bi-bug me-2"></i>Maize rust signs?
                                    </button>
                                </div>
                                <div class="col-md-4">
                                    <button class="btn btn-outline-success btn-sm w-100 text-start quick-question" 
                                            data-question="When is the best time to plant beans?">
                                        <i class="bi bi-calendar-event me-2"></i>When to plant beans?
                                    </button>
                                </div>
                                <div class="col-md-4">
                                    <button class="btn btn-outline-success btn-sm w-100 text-start quick-question" 
                                            data-question="How do I control aphids organically?">
                                        <i class="bi bi-shield-check me-2"></i>Organic pest control?
                                    </button>
                                </div>
                                <div class="col-md-4">
                                    <button class="btn btn-outline-primary btn-sm w-100 text-start quick-question" 
                                            data-question="Obulwadhe bwa muwogo ndobulaba dutya?">
                                        <i class="bi bi-translate me-2"></i>Obulwadhe bwa muwogo?
                                    </button>
                                </div>
                                <div class="col-md-4">
                                    <button class="btn btn-outline-primary btn-sm w-100 text-start quick-question" 
                                            data-question="Ndisima ditya okuzuukusa ettaka?">
                                        <i class="bi bi-translate me-2"></i>Okuzuukusa ettaka?
                                    </button>
                                </div>
                                <div class="col-md-4">
                                    <button class="btn btn-outline-info btn-sm w-100 text-start quick-question" 
                                            data-question="What is the current market price for maize?">
                                        <i class="bi bi-graph-up me-2"></i>Maize prices?
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Chat Container -->
                    <div class="card border-0 shadow-sm">
                        <div class="card-body p-0">
                            <!-- Chat Messages -->
                            <div id="chatMessages" class="p-4" style="height: 500px; overflow-y: auto; background: #f8fafc;">
                                <!-- Welcome Message -->
                                <div class="ai-message mb-3">
                                    <div class="d-flex">
                                        <div class="flex-shrink-0">
                                            <div class="bg-success text-white rounded-circle" 
                                                 style="width: 40px; height: 40px; display: flex; align-items: center; justify-content: center;">
                                                <i class="bi bi-robot"></i>
                                            </div>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <div class="bg-white rounded-3 shadow-sm p-3">
                                                <p class="mb-2">
                                                    <strong>Hello <?php echo htmlspecialchars($userName); ?>! 👋</strong>
                                                </p>
                                                <p class="mb-2">
                                                    I'm AIM AI, your intelligent agricultural assistant. I'm here to help you with:
                                                </p>
                                                <ul class="mb-2 small">
                                                    <li>🌱 Crop diseases and pest identification</li>
                                                    <li>🌾 Best farming practices and planting schedules</li>
                                                    <li>💰 Market prices and selling tips</li>
                                                    <li>🌤️ Weather information and advice</li>
                                                    <li>🔬 Soil health and fertilizer recommendations</li>
                                                    <li>🐔 Poultry and livestock care</li>
                                                </ul>
                                                <p class="mb-0 small">
                                                    <strong>Ask in English or Lusoga!</strong><br>
                                                    <em class="text-muted">Osobola okumbuuza mu Lungereza oba Lusoga!</em>
                                                </p>
                                            </div>
                                            <small class="text-muted ms-2">Just now</small>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Chat Input -->
                            <div class="border-top p-3 bg-light">
                                <form id="chatForm" class="d-flex gap-2">
                                    <div class="flex-grow-1">
                                        <textarea 
                                            id="messageInput" 
                                            class="form-control" 
                                            rows="2" 
                                            placeholder="Ask me anything about farming..."
                                            required
                                            style="resize: none;"
                                        ></textarea>
                                    </div>
                                    <div class="d-flex flex-column gap-2">
                                        <button type="submit" class="btn btn-success" id="sendButton">
                                            <i class="bi bi-send-fill"></i>
                                        </button>
                                        <button type="button" class="btn btn-outline-secondary btn-sm" 
                                                onclick="clearCurrentChat()" title="Clear chat">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </div>
                                </form>
                                <small class="text-muted">
                                    <i class="bi bi-info-circle me-1"></i>
                                    Press Enter to send • Shift+Enter for new line
                                </small>
                            </div>
                        </div>
                    </div>

                    <!-- Disclaimer -->
                    <div class="alert alert-info mt-3 mb-0">
                        <i class="bi bi-exclamation-circle me-2"></i>
                        <strong>Note:</strong> AIM AI provides general agricultural guidance. For specific issues, 
                        consult an agricultural extension officer.
                    </div>
                </div>

                <!-- HISTORY TAB -->
                <div class="tab-pane fade" id="history" role="tabpanel">
                    <div class="card border-0 shadow-sm">
                        <div class="card-header bg-white d-flex justify-content-between align-items-center">
                            <h5 class="mb-0">
                                <i class="bi bi-clock-history me-2"></i>Conversation History
                            </h5>
                            <div class="btn-group btn-group-sm" role="group">
                                <button type="button" class="btn btn-outline-primary" onclick="filterHistory('all')">
                                    All
                                </button>
                                <button type="button" class="btn btn-outline-success" onclick="filterHistory('en')">
                                    English
                                </button>
                                <button type="button" class="btn btn-outline-info" onclick="filterHistory('lusoga')">
                                    Lusoga
                                </button>
                            </div>
                        </div>
                        <div class="card-body" style="max-height: 600px; overflow-y: auto;">
                            <div id="historyContainer">
                                <div class="text-center py-5">
                                    <div class="spinner-border text-primary" role="status">
                                        <span class="visually-hidden">Loading...</span>
                                    </div>
                                    <p class="mt-2 text-muted">Loading history...</p>
                                </div>
                            </div>
                        </div>
                        <div class="card-footer bg-white text-end">
                            <button class="btn btn-outline-danger btn-sm" onclick="clearAllHistory()">
                                <i class="bi bi-trash me-1"></i>Clear All History
                            </button>
                        </div>
                    </div>
                </div>

                <!-- BEHAVIOR TAB -->
                <div class="tab-pane fade" id="behavior" role="tabpanel">
                    <div class="card border-0 shadow-sm">
                        <div class="card-header bg-white">
                            <h5 class="mb-0">
                                <i class="bi bi-sliders me-2"></i>AI Behavior Settings
                            </h5>
                        </div>
                        <div class="card-body">
                            <div class="row g-4">
                                <div class="col-md-6">
                                    <h6 class="text-muted mb-3">Response Preferences</h6>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">Preferred Language</label>
                                        <select class="form-select" id="preferredLanguage">
                                            <option value="auto">Auto-Detect</option>
                                            <option value="en">English</option>
                                            <option value="lusoga">Lusoga</option>
                                        </select>
                                        <small class="text-muted">AI will respond in this language</small>
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">Response Detail Level</label>
                                        <select class="form-select" id="detailLevel">
                                            <option value="concise">Concise (Short answers)</option>
                                            <option value="balanced" selected>Balanced (Recommended)</option>
                                            <option value="detailed">Detailed (Comprehensive)</option>
                                        </select>
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">Tone</label>
                                        <select class="form-select" id="tone">
                                            <option value="friendly" selected>Friendly</option>
                                            <option value="professional">Professional</option>
                                            <option value="casual">Casual</option>
                                        </select>
                                    </div>
                                </div>

                                <div class="col-md-6">
                                    <h6 class="text-muted mb-3">Context & Personalization</h6>
                                    
                                    <div class="form-check form-switch mb-3">
                                        <input class="form-check-input" type="checkbox" id="useContext" checked>
                                        <label class="form-check-label" for="useContext">
                                            Use my farm data for personalized responses
                                        </label>
                                    </div>

                                    <div class="form-check form-switch mb-3">
                                        <input class="form-check-input" type="checkbox" id="useHistory" checked>
                                        <label class="form-check-label" for="useHistory">
                                            Remember conversation context
                                        </label>
                                    </div>

                                    <div class="form-check form-switch mb-3">
                                        <input class="form-check-input" type="checkbox" id="suggestQuestions" checked>
                                        <label class="form-check-label" for="suggestQuestions">
                                            Show quick question suggestions
                                        </label>
                                    </div>

                                    <div class="form-check form-switch mb-3">
                                        <input class="form-check-input" type="checkbox" id="showSource">
                                        <label class="form-check-label" for="showSource">
                                            Show response source (OpenAI/Rule-based)
                                        </label>
                                    </div>
                                </div>
                            </div>

                            <hr class="my-4">

                            <div class="text-end">
                                <button class="btn btn-success" onclick="saveBehaviorSettings()">
                                    <i class="bi bi-save me-1"></i>Save Settings
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- LEARNING TAB -->
                <div class="tab-pane fade" id="learning" role="tabpanel">
                    <div class="row g-4">
                        <!-- AI Statistics -->
                        <div class="col-md-6">
                            <div class="card border-0 shadow-sm">
                                <div class="card-header bg-white">
                                    <h5 class="mb-0">
                                        <i class="bi bi-graph-up me-2"></i>Your AI Statistics
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div id="aiStats">
                                        <div class="text-center py-4">
                                            <div class="spinner-border text-primary" role="status"></div>
                                            <p class="mt-2 text-muted">Loading stats...</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Common Topics -->
                        <div class="col-md-6">
                            <div class="card border-0 shadow-sm">
                                <div class="card-header bg-white">
                                    <h5 class="mb-0">
                                        <i class="bi bi-pie-chart me-2"></i>Common Topics
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div id="commonTopics">
                                        <div class="text-center py-4">
                                            <div class="spinner-border text-primary" role="status"></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Learning Resources -->
                        <div class="col-12">
                            <div class="card border-0 shadow-sm">
                                <div class="card-header bg-white">
                                    <h5 class="mb-0">
                                        <i class="bi bi-book me-2"></i>Recommended Learning
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <p class="text-muted">Based on your questions, we recommend learning about:</p>
                                    <div id="recommendations">
                                        <div class="row g-3">
                                            <div class="col-md-4">
                                                <div class="border rounded p-3">
                                                    <h6>Crop Disease Management</h6>
                                                    <p class="small text-muted mb-2">Learn to identify and treat common diseases</p>
                                                    <a href="/learning/diseases.php" class="btn btn-sm btn-outline-success">Learn More</a>
                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <div class="border rounded p-3">
                                                    <h6>Planting Schedules</h6>
                                                    <p class="small text-muted mb-2">Optimize your planting calendar</p>
                                                    <a href="/learning/schedules.php" class="btn btn-sm btn-outline-success">Learn More</a>
                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <div class="border rounded p-3">
                                                    <h6>Market Intelligence</h6>
                                                    <p class="small text-muted mb-2">Get better prices for your produce</p>
                                                    <a href="/prices/" class="btn btn-sm btn-outline-success">Learn More</a>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
/* Animations */
.ai-message {
    animation: fadeIn 0.3s ease-in;
}

.user-message {
    animation: slideIn 0.3s ease-out;
}

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

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

/* Quick questions */
.quick-question {
    transition: all 0.2s ease;
}

.quick-question:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

/* Scrollbar */
#chatMessages::-webkit-scrollbar {
    width: 8px;
}

#chatMessages::-webkit-scrollbar-track {
    background: #f1f1f1;
}

#chatMessages::-webkit-scrollbar-thumb {
    background: #888;
    border-radius: 4px;
}

#chatMessages::-webkit-scrollbar-thumb:hover {
    background: #555;
}

/* Typing indicator */
.typing-indicator {
    display: inline-block;
}

.typing-indicator span {
    height: 8px;
    width: 8px;
    background-color: #059669;
    border-radius: 50%;
    display: inline-block;
    margin: 0 2px;
    animation: typing 1.4s infinite;
}

.typing-indicator span:nth-child(2) {
    animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
    animation-delay: 0.4s;
}

@keyframes typing {
    0%, 60%, 100% {
        transform: translateY(0);
        opacity: 0.7;
    }
    30% {
        transform: translateY(-10px);
        opacity: 1;
    }
}

/* History items */
.history-item {
    transition: all 0.2s ease;
}

.history-item:hover {
    background-color: #f8f9fa !important;
    cursor: pointer;
}

/* Nav tabs enhancement */
.nav-tabs .nav-link {
    border-radius: 0;
    border: none;
    border-bottom: 3px solid transparent;
    color: #6c757d;
}

.nav-tabs .nav-link:hover {
    border-bottom-color: #059669;
    color: #059669;
}

.nav-tabs .nav-link.active {
    background: none;
    border-bottom-color: #059669;
    color: #059669;
    font-weight: 600;
}
</style>

<script>
// Define constants ONCE at the top
const APP_URL = '<?php echo APP_URL; ?>';
const USER_ID = <?php echo $userId; ?>;
const USER_TYPE = '<?php echo $userType; ?>';

$(document).ready(function() {
    // Load behavior settings from localStorage
    loadBehaviorSettings();
    
    // Handle quick questions
    $('.quick-question').click(function() {
        const question = $(this).data('question');
        $('#messageInput').val(question);
        $('#chatForm').submit();
    });
    
    // Handle chat form submission
    $('#chatForm').submit(function(e) {
        e.preventDefault();
        sendMessage();
    });
    
    // Handle Enter key
    $('#messageInput').keydown(function(e) {
        if (e.keyCode === 13 && !e.shiftKey) {
            e.preventDefault();
            $('#chatForm').submit();
        }
    });

    // Load history when history tab is shown
    $('button[data-bs-target="#history"]').on('shown.bs.tab', function() {
        loadHistory();
    });

    // Load learning stats when learning tab is shown
    $('button[data-bs-target="#learning"]').on('shown.bs.tab', function() {
        loadStats();
    });
});

// Send message function
function sendMessage() {
    const message = $('#messageInput').val().trim();
    if (!message) return;
    
    // Add user message to chat
    addUserMessage(message);
    
    // Clear input
    $('#messageInput').val('');
    
    // Show typing indicator
    showTypingIndicator();
    
    // Send to AI
    $.ajax({
        url: APP_URL + '/ai-assistant/ajax/chat.php',
        type: 'POST',
        data: {
            message: message,
            user_id: USER_ID,
            user_type: USER_TYPE
        },
        dataType: 'json',
        success: function(response) {
            removeTypingIndicator();
            
            if (response.success) {
                addAIMessage(response.response, response.language, response.source);
            } else {
                addAIMessage('Sorry, I encountered an error. Please try again.', 'en');
                showToast(response.message || 'Error processing request', 'error');
            }
        },
        error: function(xhr, status, error) {
            removeTypingIndicator();
            addAIMessage('Sorry, I\'m having trouble connecting. Please check your internet and try again.', 'en');
            showToast('Connection error', 'error');
        }
    });
}

// Add user message to chat
function addUserMessage(message) {
    const time = new Date().toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
    const html = `
        <div class="user-message mb-3">
            <div class="d-flex justify-content-end">
                <div class="flex-grow-1 me-3 text-end">
                    <div class="bg-success text-white rounded-3 shadow-sm p-3 d-inline-block" 
                         style="max-width: 80%; text-align: left;">
                        ${escapeHtml(message).replace(/\n/g, '<br>')}
                    </div>
                    <br><small class="text-muted me-2">${time}</small>
                </div>
                <div class="flex-shrink-0">
                    <div class="bg-primary text-white rounded-circle" 
                         style="width: 40px; height: 40px; display: flex; align-items: center; justify-content: center;">
                        <i class="bi bi-person-fill"></i>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    $('#chatMessages').append(html);
    scrollToBottom();
}

// Add AI message to chat
function addAIMessage(message, language = 'en', source = null) {
    const time = new Date().toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
    const showSource = $('#showSource').is(':checked');
    
    let sourceBadge = '';
    if (showSource && source) {
        const badgeClass = source === 'openai' ? 'bg-info' : 'bg-secondary';
        const badgeText = source === 'openai' ? 'OpenAI' : 'Rule-based';
        sourceBadge = `<span class="badge ${badgeClass} ms-2">${badgeText}</span>`;
    }
    
    const html = `
        <div class="ai-message mb-3">
            <div class="d-flex">
                <div class="flex-shrink-0">
                    <div class="bg-success text-white rounded-circle" 
                         style="width: 40px; height: 40px; display: flex; align-items: center; justify-content: center;">
                        <i class="bi bi-robot"></i>
                    </div>
                </div>
                <div class="flex-grow-1 ms-3">
                    <div class="bg-white rounded-3 shadow-sm p-3">
                        ${formatAIResponse(message)}
                    </div>
                    <small class="text-muted ms-2">${time}</small>
                    ${language === 'lusoga' ? '<span class="badge bg-primary ms-2">Lusoga</span>' : ''}
                    ${sourceBadge}
                </div>
            </div>
        </div>
    `;
    
    $('#chatMessages').append(html);
    scrollToBottom();
}

// Show typing indicator
function showTypingIndicator() {
    const html = `
        <div class="ai-message mb-3" id="typingIndicator">
            <div class="d-flex">
                <div class="flex-shrink-0">
                    <div class="bg-success text-white rounded-circle" 
                         style="width: 40px; height: 40px; display: flex; align-items: center; justify-content: center;">
                        <i class="bi bi-robot"></i>
                    </div>
                </div>
                <div class="flex-grow-1 ms-3">
                    <div class="bg-white rounded-3 shadow-sm p-3">
                        <div class="typing-indicator">
                            <span></span>
                            <span></span>
                            <span></span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    $('#chatMessages').append(html);
    scrollToBottom();
}

// Remove typing indicator
function removeTypingIndicator() {
    $('#typingIndicator').remove();
}

// Format AI response
function formatAIResponse(text) {
    let formatted = escapeHtml(text);
    
    // Bold
    formatted = formatted.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
    
    // Lists
    formatted = formatted.replace(/^- (.+)$/gm, '<li>$1</li>');
    formatted = formatted.replace(/(<li>.*?<\/li>)/s, '<ul class="mb-0">$1</ul>');
    
    // Line breaks
    formatted = formatted.replace(/\n/g, '<br>');
    
    return formatted;
}

// Escape HTML
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// Scroll to bottom
function scrollToBottom() {
    const chatMessages = document.getElementById('chatMessages');
    chatMessages.scrollTop = chatMessages.scrollHeight;
}

// Clear current chat
function clearCurrentChat() {
    if (confirm('Clear current conversation? This cannot be undone.')) {
        $('#chatMessages .ai-message:not(:first), #chatMessages .user-message').remove();
        showToast('Chat cleared', 'success');
    }
}

// Load conversation history
function loadHistory(filter = 'all') {
    $.ajax({
        url: APP_URL + '/ai-assistant/ajax/history.php',
        type: 'GET',
        data: { filter: filter },
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                displayHistory(response.conversations);
            } else {
                $('#historyContainer').html('<p class="text-muted text-center">No history found</p>');
            }
        },
        error: function() {
            $('#historyContainer').html('<p class="text-danger text-center">Error loading history</p>');
        }
    });
}

// Display history
function displayHistory(conversations) {
    if (conversations.length === 0) {
        $('#historyContainer').html('<p class="text-muted text-center py-4">No conversations yet</p>');
        return;
    }
    
    let html = '';
    conversations.forEach(function(conv) {
        const langBadge = conv.language === 'lusoga' ? 
            '<span class="badge bg-primary">Lusoga</span>' : 
            '<span class="badge bg-success">English</span>';
        
        html += `
            <div class="history-item border-bottom pb-3 mb-3">
                <div class="d-flex justify-content-between align-items-start">
                    <div class="flex-grow-1">
                        <p class="mb-1"><strong>You:</strong> ${escapeHtml(conv.message).substring(0, 100)}...</p>
                        <p class="mb-1 text-muted small"><strong>AI:</strong> ${escapeHtml(conv.response).substring(0, 150)}...</p>
                        <small class="text-muted">${conv.created_at}</small>
                    </div>
                    <div>
                        ${langBadge}
                    </div>
                </div>
            </div>
        `;
    });
    
    $('#historyContainer').html(html);
}

// Filter history
function filterHistory(filter) {
    loadHistory(filter);
}

// Clear all history
function clearAllHistory() {
    if (confirm('Delete all conversation history? This cannot be undone.')) {
        $.ajax({
            url: APP_URL + '/ai-assistant/ajax/clear-history.php',
            type: 'POST',
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    showToast('History cleared successfully', 'success');
                    loadHistory();
                } else {
                    showToast('Error clearing history', 'error');
                }
            }
        });
    }
}

// Load AI statistics
function loadStats() {
    $.ajax({
        url: APP_URL + '/ai-assistant/ajax/stats.php',
        type: 'GET',
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                displayStats(response.stats);
            }
        }
    });
}

// Display statistics
function displayStats(stats) {
    const html = `
        <div class="row g-3">
            <div class="col-6">
                <div class="text-center p-3 border rounded">
                    <h3 class="text-success mb-0">${stats.total_conversations || 0}</h3>
                    <small class="text-muted">Total Conversations</small>
                </div>
            </div>
            <div class="col-6">
                <div class="text-center p-3 border rounded">
                    <h3 class="text-primary mb-0">${stats.lusoga_count || 0}</h3>
                    <small class="text-muted">Lusoga Questions</small>
                </div>
            </div>
            <div class="col-6">
                <div class="text-center p-3 border rounded">
                    <h3 class="text-info mb-0">${stats.english_count || 0}</h3>
                    <small class="text-muted">English Questions</small>
                </div>
            </div>
            <div class="col-6">
                <div class="text-center p-3 border rounded">
                    <h3 class="text-warning mb-0">${stats.openai_count || 0}</h3>
                    <small class="text-muted">OpenAI Responses</small>
                </div>
            </div>
        </div>
    `;
    
    $('#aiStats').html(html);
}

// Save behavior settings
function saveBehaviorSettings() {
    const settings = {
        preferredLanguage: $('#preferredLanguage').val(),
        detailLevel: $('#detailLevel').val(),
        tone: $('#tone').val(),
        useContext: $('#useContext').is(':checked'),
        useHistory: $('#useHistory').is(':checked'),
        suggestQuestions: $('#suggestQuestions').is(':checked'),
        showSource: $('#showSource').is(':checked')
    };
    
    localStorage.setItem('ai_behavior_settings', JSON.stringify(settings));
    showToast('Settings saved successfully', 'success');
}

// Load behavior settings
function loadBehaviorSettings() {
    const saved = localStorage.getItem('ai_behavior_settings');
    if (saved) {
        const settings = JSON.parse(saved);
        $('#preferredLanguage').val(settings.preferredLanguage || 'auto');
        $('#detailLevel').val(settings.detailLevel || 'balanced');
        $('#tone').val(settings.tone || 'friendly');
        $('#useContext').prop('checked', settings.useContext !== false);
        $('#useHistory').prop('checked', settings.useHistory !== false);
        $('#suggestQuestions').prop('checked', settings.suggestQuestions !== false);
        $('#showSource').prop('checked', settings.showSource || false);
    }
}
</script>

<?php include __DIR__ . '/../includes/bottom-nav.php'; ?>
<?php include __DIR__ . '/../includes/footer.php'; ?>