<?php
/**
 * ============================================================================
 * ai-assistant/index.php - AIM AI Assistant Interface
 * ============================================================================
 */

// 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-8 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 - Ask me anything in English or Lusoga!</p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Quick Actions -->
            <div class="card border-0 shadow-sm mb-4">
                <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">
                        <!-- English Questions -->
                        <div class="col-md-6">
                            <button class="btn btn-outline-success 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 disease signs?
                            </button>
                        </div>
                        <div class="col-md-6">
                            <button class="btn btn-outline-success w-100 text-start quick-question" 
                                    data-question="When is the best time to plant beans in Uganda?">
                                <i class="bi bi-calendar-event me-2"></i>When to plant beans?
                            </button>
                        </div>
                        <div class="col-md-6">
                            <button class="btn btn-outline-success w-100 text-start quick-question" 
                                    data-question="How do I control aphids on vegetables organically?">
                                <i class="bi bi-shield-check me-2"></i>Organic aphid control?
                            </button>
                        </div>
                        <div class="col-md-6">
                            <button class="btn btn-outline-success 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 market prices?
                            </button>
                        </div>
                        <!-- Lusoga Questions -->
                        <div class="col-md-6">
                            <button class="btn btn-outline-primary w-100 text-start quick-question" 
                                    data-question="Obulwadhe bwa cassava brown streak ndobulaba dutya?">
                                <i class="bi bi-translate me-2"></i>Obulwadhe bwa muwogo?
                            </button>
                        </div>
                        <div class="col-md-6">
                            <button class="btn btn-outline-primary w-100 text-start quick-question" 
                                    data-question="Ndisima ditya okuzuukusa amasimu gange?">
                                <i class="bi bi-translate me-2"></i>Okuzuukusa amasimu?
                            </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">
                                            <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">
                                            <strong>You can ask me questions in English or Lusoga!</strong><br>
                                            <em class="text-muted">Osobola okumbuuza ebibuuzo 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">
                        <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... (English or Lusoga)"
                                    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" 
                                        onclick="clearChat()" 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">
                <i class="bi bi-exclamation-circle me-2"></i>
                <strong>Note:</strong> AIM AI provides general agricultural guidance. For specific issues or complex problems, 
                please consult with an agricultural extension officer or specialist.
            </div>
        </div>
    </div>
</div>

<style>
.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-question:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.quick-question {
    transition: all 0.2s ease;
}

#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 {
    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;
    }
}
</style>

<script>
$(document).ready(function() {
    // 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();
        
        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: <?php echo $userId; ?>,
                user_type: '<?php echo $userType; ?>'
            },
            dataType: 'json',
            success: function(response) {
                removeTypingIndicator();
                
                if (response.success) {
                    addAIMessage(response.response, response.language);
                } 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');
            }
        });
    });
    
    // Handle Enter key
    $('#messageInput').keydown(function(e) {
        if (e.keyCode === 13 && !e.shiftKey) {
            e.preventDefault();
            $('#chatForm').submit();
        }
    });
});

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();
}

function addAIMessage(message, language = 'en') {
    const time = new Date().toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
    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>' : ''}
                </div>
            </div>
        </div>
    `;
    
    $('#chatMessages').append(html);
    scrollToBottom();
}

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();
}

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

function formatAIResponse(text) {
    // Convert markdown-style formatting to HTML
    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>$1</ul>');
    
    // Line breaks
    formatted = formatted.replace(/\n/g, '<br>');
    
    // Numbers
    formatted = formatted.replace(/\b(\d+)\b/g, '<strong>$1</strong>');
    
    return formatted;
}

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

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

function clearChat() {
    confirmAction(
        'Clear Chat History',
        'Are you sure you want to clear the chat? This cannot be undone.',
        function() {
            // Keep only the welcome message
            $('#chatMessages .ai-message:not(:first), #chatMessages .user-message').remove();
            showToast('Chat cleared', 'success');
        }
    );
}
</script>

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