<?php
/**
 * ============================================================================
 * ai-assistant/index.php - Production AI Assistant (ChatGPT-style Sessions)
 * ============================================================================
 */

define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

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

$userId = getUserId();
$userName = getUserName();
$userType = getUserType();
$pageTitle = 'AIM AI Assistant';

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

<!-- Google Fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">

<style>
:root {
    --chat-primary: #10a37f;
    --chat-primary-hover: #0d8968;
    --chat-bg: #ffffff;
    --chat-sidebar-bg: #f7f7f8;
    --chat-user-msg: #f4f4f4;
    --chat-ai-msg: #ffffff;
    --chat-border: #e5e5e5;
    --chat-text: #2d333a;
    --chat-text-light: #676b79;
    --chat-input-bg: #ffffff;
}

[data-theme="dark"] {
    --chat-bg: #212121;
    --chat-sidebar-bg: #171717;
    --chat-user-msg: #2f2f2f;
    --chat-ai-msg: #2f2f2f;
    --chat-border: #3d3d3d;
    --chat-text: #ececec;
    --chat-text-light: #b4b4b4;
    --chat-input-bg: #2f2f2f;
}

body {
    font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
    background: var(--chat-bg);
    color: var(--chat-text);
}

.chat-container {
    display: flex;
    height: calc(100vh - 70px);
}

.chat-sidebar {
    width: 280px;
    background: var(--chat-sidebar-bg);
    border-right: 1px solid var(--chat-border);
    display: flex;
    flex-direction: column;
}

.chat-sidebar-header {
    padding: 20px;
    border-bottom: 1px solid var(--chat-border);
}

.new-chat-btn {
    width: 100%;
    padding: 12px 16px;
    background: var(--chat-primary);
    color: white;
    border: none;
    border-radius: 8px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
}

.new-chat-btn:hover {
    background: var(--chat-primary-hover);
}

.sidebar-tabs {
    display: flex;
    padding: 8px;
    gap: 4px;
    border-bottom: 1px solid var(--chat-border);
}

.sidebar-tab {
    flex: 1;
    padding: 8px;
    background: transparent;
    border: none;
    border-radius: 6px;
    font-size: 13px;
    cursor: pointer;
    color: var(--chat-text-light);
    transition: all 0.2s;
}

.sidebar-tab.active {
    background: var(--chat-user-msg);
    color: var(--chat-text);
    font-weight: 500;
}

.sidebar-content {
    flex: 1;
    overflow-y: auto;
    padding: 12px;
}

.history-item {
    padding: 12px;
    margin-bottom: 4px;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.2s;
    font-size: 14px;
}

.history-item:hover {
    background: var(--chat-user-msg);
}

.history-item.active {
    background: var(--chat-user-msg);
    font-weight: 500;
}

.chat-main {
    flex: 1;
    display: flex;
    flex-direction: column;
    background: var(--chat-bg);
}

.chat-header {
    padding: 16px 24px;
    border-bottom: 1px solid var(--chat-border);
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.chat-title {
    font-size: 18px;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 12px;
}

.chat-model-badge {
    padding: 4px 12px;
    background: var(--chat-primary);
    color: white;
    border-radius: 12px;
    font-size: 11px;
}

.api-status {
    font-size: 11px;
    padding: 4px 10px;
    border-radius: 10px;
    display: inline-flex;
    align-items: center;
    gap: 4px;
}

.api-status.active {
    background: #dcfce7;
    color: #166534;
}

.api-status.inactive {
    background: #fee2e2;
    color: #991b1b;
}

.chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 24px;
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.message-group {
    display: flex;
    gap: 12px;
    animation: messageSlideIn 0.4s cubic-bezier(0.16, 1, 0.3, 1);
}

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

.message-avatar {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    font-size: 16px;
}

.message-avatar.user {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
}

.message-avatar.ai {
    background: linear-gradient(135deg, #10a37f 0%, #0d8968 100%);
    color: white;
}

.message-content {
    flex: 1;
    max-width: 780px;
}

.message-header {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 6px;
}

.message-author {
    font-weight: 600;
    font-size: 13px;
}

.message-time {
    font-size: 11px;
    color: var(--chat-text-light);
}

.message-text {
    line-height: 1.6;
    font-size: 15px;
}

.message-text p {
    margin: 0 0 10px 0;
}

.message-text strong {
    font-weight: 600;
}

.message-text ul, .message-text ol {
    margin: 8px 0;
    padding-left: 20px;
}

.typing-indicator {
    display: flex;
    gap: 4px;
    padding: 10px 0;
}

.typing-dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: var(--chat-text-light);
    animation: typingBounce 1.4s infinite ease-in-out;
}

.typing-dot:nth-child(2) { animation-delay: 0.2s; }
.typing-dot:nth-child(3) { animation-delay: 0.4s; }

@keyframes typingBounce {
    0%, 60%, 100% { transform: translateY(0); }
    30% { transform: translateY(-8px); }
}

.streaming-cursor {
    display: inline-block;
    width: 2px;
    height: 1em;
    background: var(--chat-text);
    margin-left: 2px;
    animation: cursorBlink 1s infinite;
    vertical-align: text-bottom;
}

@keyframes cursorBlink {
    0%, 49% { opacity: 1; }
    50%, 100% { opacity: 0; }
}

.chat-input-container {
    padding: 16px 24px 24px;
    background: var(--chat-bg);
    border-top: 1px solid var(--chat-border);
}

.quick-prompts {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
    margin-bottom: 12px;
    max-width: 780px;
    margin-left: auto;
    margin-right: auto;
}

.quick-prompt {
    padding: 6px 14px;
    background: var(--chat-user-msg);
    border: 1px solid var(--chat-border);
    border-radius: 16px;
    font-size: 13px;
    cursor: pointer;
    transition: all 0.2s;
}

.quick-prompt:hover {
    background: var(--chat-border);
    transform: translateY(-2px);
}

.chat-input-wrapper {
    max-width: 780px;
    margin: 0 auto;
    position: relative;
}

.chat-input {
    width: 100%;
    min-height: 52px;
    max-height: 200px;
    padding: 14px 52px 14px 16px;
    background: var(--chat-input-bg);
    border: 1px solid var(--chat-border);
    border-radius: 12px;
    font-size: 15px;
    font-family: 'Inter', sans-serif;
    color: var(--chat-text);
    resize: none;
    transition: all 0.2s;
}

.chat-input:focus {
    outline: none;
    border-color: var(--chat-primary);
    box-shadow: 0 0 0 3px rgba(16, 163, 127, 0.1);
}

.send-button {
    position: absolute;
    right: 8px;
    bottom: 8px;
    width: 36px;
    height: 36px;
    background: var(--chat-primary);
    border: none;
    border-radius: 8px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
}

.send-button:hover:not(:disabled) {
    background: var(--chat-primary-hover);
}

.send-button:disabled {
    opacity: 0.4;
    cursor: not-allowed;
}

.welcome-screen {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    text-align: center;
    padding: 40px;
}

.welcome-icon {
    width: 80px;
    height: 80px;
    background: linear-gradient(135deg, #10a37f 0%, #0d8968 100%);
    border-radius: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 40px;
    margin-bottom: 24px;
}

.welcome-title {
    font-size: 32px;
    font-weight: 700;
    margin-bottom: 12px;
    background: linear-gradient(135deg, #10a37f 0%, #667eea 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}

.welcome-subtitle {
    font-size: 16px;
    color: var(--chat-text-light);
    margin-bottom: 32px;
    max-width: 500px;
}

.language-badge {
    padding: 2px 8px;
    background: #667eea;
    color: white;
    border-radius: 4px;
    font-size: 10px;
}

.source-badge {
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 10px;
}

.source-badge.openai {
    background: #10a37f;
    color: white;
}

.source-badge.rule-based {
    background: #94a3b8;
    color: white;
}
</style>

<div class="chat-container">
    <aside class="chat-sidebar">
        <div class="chat-sidebar-header">
            <button class="new-chat-btn" onclick="startNewChat()">
                <i class="bi bi-plus-lg"></i>
                New Chat
            </button>
        </div>
        
        <div class="sidebar-tabs">
            <button class="sidebar-tab active" onclick="switchSidebarTab('history')" data-tab="history">
                History
            </button>
            <button class="sidebar-tab" onclick="switchSidebarTab('settings')" data-tab="settings">
                Settings
            </button>
        </div>
        
        <div class="sidebar-content" id="sidebarContent"></div>
        
        <div style="padding: 16px; border-top: 1px solid var(--chat-border);">
            <button class="sidebar-tab" style="width: 100%;" onclick="toggleTheme()">
                <i class="bi bi-moon-stars me-2"></i> Theme
            </button>
        </div>
    </aside>

    <main class="chat-main">
        <div class="chat-header">
            <div class="chat-title">
                <i class="bi bi-robot"></i>
                AIM AI Assistant
                <span class="chat-model-badge">GPT-3.5</span>
                <span class="api-status" id="apiStatus">
                    <i class="bi bi-circle-fill" style="font-size: 6px;"></i>
                    <span id="apiStatusText">Checking...</span>
                </span>
            </div>
        </div>

        <div class="chat-messages" id="chatMessages">
            <div class="welcome-screen" id="welcomeScreen">
                <div class="welcome-icon">🌾</div>
                <h1 class="welcome-title">Welcome, <?php echo htmlspecialchars($userName); ?>!</h1>
                <p class="welcome-subtitle">
                    Your intelligent agricultural assistant for Uganda. Ask me anything in English or Lusoga!
                </p>
                <div class="quick-prompts">
                    <div class="quick-prompt" onclick="sendQuickPrompt(this)">🌱 Best time to plant maize</div>
                    <div class="quick-prompt" onclick="sendQuickPrompt(this)">🐛 Maize rust disease</div>
                    <div class="quick-prompt" onclick="sendQuickPrompt(this)">💰 Market prices</div>
                    <div class="quick-prompt" onclick="sendQuickPrompt(this)">Obulwadhe bwa muwogo</div>
                </div>
            </div>
        </div>

        <div class="chat-input-container">
            <div class="chat-input-wrapper">
                <textarea 
                    class="chat-input" 
                    id="messageInput" 
                    placeholder="Ask me anything about farming..."
                    rows="1"
                ></textarea>
                <button class="send-button" id="sendButton" onclick="sendMessage()" disabled>
                    <i class="bi bi-send-fill"></i>
                </button>
            </div>
        </div>
    </main>
</div>

<script>
const APP_URL = '<?php echo APP_URL; ?>';
const USER_ID = <?php echo $userId; ?>;

let isStreaming = false;
let currentSessionId = null; // Current conversation session
let currentSessions = [];

$(document).ready(function() {
    const textarea = document.getElementById('messageInput');
    textarea.addEventListener('input', function() {
        this.style.height = 'auto';
        this.style.height = (this.scrollHeight) + 'px';
        updateSendButton();
    });

    textarea.addEventListener('keydown', function(e) {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            sendMessage();
        }
    });

    loadSidebarContent('history');
    checkAPIStatus();
    setInterval(checkAPIStatus, 30000);
});

function updateSendButton() {
    const sendBtn = document.getElementById('sendButton');
    sendBtn.disabled = !document.getElementById('messageInput').value.trim() || isStreaming;
}

function checkAPIStatus() {
    $.ajax({
        url: APP_URL + '/ai-assistant/ajax/check-api.php',
        type: 'GET',
        dataType: 'json',
        success: function(response) {
            const statusEl = document.getElementById('apiStatus');
            const statusTextEl = document.getElementById('apiStatusText');
            
            if (response.configured) {
                statusEl.className = 'api-status active';
                statusTextEl.textContent = 'OpenAI Active';
            } else {
                statusEl.className = 'api-status inactive';
                statusTextEl.textContent = 'Knowledge Base';
            }
        }
    });
}

function sendMessage() {
    const input = document.getElementById('messageInput');
    const message = input.value.trim();
    
    if (!message || isStreaming) return;
    
    $('#welcomeScreen').fadeOut(300, function() { $(this).remove(); });
    
    addUserMessage(message);
    input.value = '';
    input.style.height = 'auto';
    updateSendButton();
    
    showTypingIndicator();
    
    setTimeout(() => {
        $.ajax({
            url: APP_URL + '/ai-assistant/ajax/chat.php',
            type: 'POST',
            data: {
                message: message,
                user_id: USER_ID,
                session_id: currentSessionId
            },
            dataType: 'json',
            success: function(response) {
                removeTypingIndicator();
                
                if (response.success) {
                    // Store session ID for continuing conversation
                    currentSessionId = response.session_id;
                    streamAIMessage(response.response, response.language, response.source);
                    // Refresh history
                    if (currentSidebarTab === 'history') {
                        setTimeout(() => loadSidebarContent('history'), 500);
                    }
                } else {
                    addAIMessage('Sorry, error occurred. Try again.', 'en', null);
                }
            },
            error: function(xhr) {
                removeTypingIndicator();
                console.error('Error:', xhr.responseText);
                addAIMessage('Connection error. Check internet.', 'en', null);
            }
        });
    }, 300);
}

function addUserMessage(message) {
    const time = new Date().toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
    const html = `
        <div class="message-group">
            <div class="message-avatar user"><i class="bi bi-person-fill"></i></div>
            <div class="message-content">
                <div class="message-header">
                    <span class="message-author">You</span>
                    <span class="message-time">${time}</span>
                </div>
                <div class="message-text">${escapeHtml(message).replace(/\n/g, '<br>')}</div>
            </div>
        </div>
    `;
    $('#chatMessages').append(html);
    scrollToBottom();
}

function streamAIMessage(message, language = 'en', source = null) {
    isStreaming = true;
    updateSendButton();
    
    const time = new Date().toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
    const langBadge = language === 'lusoga' ? '<span class="language-badge">Lusoga</span>' : '';
    
    let sourceBadge = '';
    if (source) {
        const badgeClass = source === 'openai' ? 'openai' : 'rule-based';
        const badgeText = source === 'openai' ? 'OpenAI' : 'Knowledge Base';
        sourceBadge = `<span class="source-badge ${badgeClass}">${badgeText}</span>`;
    }
    
    const messageId = 'msg-' + Date.now();
    const html = `
        <div class="message-group" id="${messageId}">
            <div class="message-avatar ai"><i class="bi bi-robot"></i></div>
            <div class="message-content">
                <div class="message-header">
                    <span class="message-author">AIM AI</span>
                    ${langBadge}
                    ${sourceBadge}
                    <span class="message-time">${time}</span>
                </div>
                <div class="message-text" id="${messageId}-text"></div>
            </div>
        </div>
    `;
    
    $('#chatMessages').append(html);
    const element = document.getElementById(`${messageId}-text`);
    
    streamText(element, formatAIResponse(message), () => {
        isStreaming = false;
        updateSendButton();
    });
    
    scrollToBottom();
}

function streamText(element, html, callback) {
    const tempDiv = document.createElement('div');
    tempDiv.innerHTML = html;
    const text = tempDiv.textContent || tempDiv.innerText;
    
    let index = 0;
    const speed = 25;
    
    const cursor = document.createElement('span');
    cursor.className = 'streaming-cursor';
    element.appendChild(cursor);
    
    function typeChar() {
        if (index < text.length) {
            cursor.remove();
            
            const span = document.createElement('span');
            span.textContent = text[index];
            element.appendChild(span);
            element.appendChild(cursor);
            
            index++;
            
            let delay = speed;
            const char = text[index - 1];
            if (char === '.' || char === '!' || char === '?') delay = speed * 4;
            else if (char === ',' || char === ';') delay = speed * 2;
            
            setTimeout(typeChar, delay);
            if (index % 3 === 0) scrollToBottom();
        } else {
            cursor.remove();
            element.innerHTML = html;
            scrollToBottom();
            callback();
        }
    }
    
    typeChar();
}

function addAIMessage(message, language, source) {
    const time = new Date().toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
    const langBadge = language === 'lusoga' ? '<span class="language-badge">Lusoga</span>' : '';
    
    let sourceBadge = '';
    if (source) {
        const badgeClass = source === 'openai' ? 'openai' : 'rule-based';
        const badgeText = source === 'openai' ? 'OpenAI' : 'Knowledge Base';
        sourceBadge = `<span class="source-badge ${badgeClass}">${badgeText}</span>`;
    }
    
    const html = `
        <div class="message-group">
            <div class="message-avatar ai"><i class="bi bi-robot"></i></div>
            <div class="message-content">
                <div class="message-header">
                    <span class="message-author">AIM AI</span>
                    ${langBadge}
                    ${sourceBadge}
                    <span class="message-time">${time}</span>
                </div>
                <div class="message-text">${formatAIResponse(message)}</div>
            </div>
        </div>
    `;
    
    $('#chatMessages').append(html);
    scrollToBottom();
}

function showTypingIndicator() {
    const html = `
        <div class="message-group" id="typingIndicator">
            <div class="message-avatar ai"><i class="bi bi-robot"></i></div>
            <div class="message-content">
                <div class="message-header">
                    <span class="message-author">AIM AI</span>
                    <span class="message-time">typing...</span>
                </div>
                <div class="typing-indicator">
                    <span class="typing-dot"></span>
                    <span class="typing-dot"></span>
                    <span class="typing-dot"></span>
                </div>
            </div>
        </div>
    `;
    $('#chatMessages').append(html);
    scrollToBottom();
}

function removeTypingIndicator() {
    $('#typingIndicator').remove();
}

function formatAIResponse(text) {
    let formatted = escapeHtml(text);
    formatted = formatted.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
    formatted = formatted.replace(/^- (.+)$/gm, '<li>$1</li>');
    formatted = formatted.replace(/(<li>.*?<\/li>)/s, '<ul>$1</ul>');
    formatted = formatted.replace(/\n\n/g, '</p><p>');
    formatted = '<p>' + formatted + '</p>';
    return formatted;
}

function sendQuickPrompt(element) {
    const prompt = element.textContent.trim().replace(/^[🌱🐛💰]+\s*/, '');
    document.getElementById('messageInput').value = prompt;
    sendMessage();
}

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

function scrollToBottom() {
    const messages = document.getElementById('chatMessages');
    messages.scrollTop = messages.scrollHeight;
}

let currentSidebarTab = 'history';

function switchSidebarTab(tab) {
    currentSidebarTab = tab;
    $('.sidebar-tab').removeClass('active');
    $(`.sidebar-tab[data-tab="${tab}"]`).addClass('active');
    loadSidebarContent(tab);
}

function loadSidebarContent(tab) {
    const container = $('#sidebarContent');
    
    if (tab === 'history') {
        container.html('<div class="text-center py-4"><div class="spinner-border spinner-border-sm"></div></div>');
        
        $.ajax({
            url: APP_URL + '/ai-assistant/ajax/history.php',
            type: 'GET',
            dataType: 'json',
            success: function(response) {
                if (response.success && response.sessions.length > 0) {
                    currentSessions = response.sessions;
                    displayHistory(response.sessions);
                } else {
                    container.html('<div class="text-center py-4 text-muted" style="font-size: 13px;">No conversations yet</div>');
                }
            }
        });
    } else {
        container.html('<div style="padding: 8px; font-size: 13px; color: var(--chat-text-light);">Settings coming soon...</div>');
    }
}

function displayHistory(sessions) {
    let html = '';
    sessions.forEach(session => {
        const preview = session.first_message.substring(0, 35) + (session.first_message.length > 35 ? '...' : '');
        const date = new Date(session.started_at).toLocaleDateString();
        html += `
            <div class="history-item" onclick="loadSession('${session.session_id}')" data-session="${session.session_id}">
                <div style="display: flex; align-items: start; gap: 8px;">
                    <i class="bi bi-chat-left-text" style="margin-top: 2px;"></i>
                    <div style="flex: 1;">
                        <div style="font-size: 13px; margin-bottom: 4px;">${escapeHtml(preview)}</div>
                        <div style="font-size: 11px; color: var(--chat-text-light);">${date} • ${session.message_count} msgs</div>
                    </div>
                </div>
            </div>
        `;
    });
    $('#sidebarContent').html(html);
}

function loadSession(sessionId) {
    // Clear current chat
    $('#chatMessages').empty();
    currentSessionId = sessionId;
    
    // Load session messages
    $.ajax({
        url: APP_URL + '/ai-assistant/ajax/load-session.php',
        type: 'GET',
        data: { session_id: sessionId },
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                response.messages.forEach(msg => {
                    addUserMessage(msg.message);
                    addAIMessage(msg.response, msg.language, msg.source);
                });
            }
        }
    });
    
    // Highlight in sidebar
    $('.history-item').removeClass('active');
    $(`.history-item[data-session="${sessionId}"]`).addClass('active');
}

function startNewChat() {
    currentSessionId = null;
    $('#chatMessages').empty();
    $('#chatMessages').html(`
        <div class="welcome-screen">
            <div class="welcome-icon">🌾</div>
            <h1 class="welcome-title">New Conversation</h1>
            <p class="welcome-subtitle">What would you like to know about farming?</p>
        </div>
    `);
    $('.history-item').removeClass('active');
}

function toggleTheme() {
    const html = document.documentElement;
    const current = html.getAttribute('data-theme');
    html.setAttribute('data-theme', current === 'dark' ? 'light' : 'dark');
    localStorage.setItem('theme', current === 'dark' ? 'light' : 'dark');
}

const savedTheme = localStorage.getItem('theme') || 'light';
document.documentElement.setAttribute('data-theme', savedTheme);
</script>

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