<?php
/**
 * ============================================================================
 * AIAssistant.php - Smart Agricultural AI Assistant
 * ============================================================================
 * Features:
 * - Intelligent query classification
 * - Multi-source knowledge retrieval
 * - Database-powered responses
 * - Fallback systems for development
 * - No external API dependencies required
 */

namespace App;

class AIAssistant {
    private $db;
    private $openaiApiKey;
    private $model;
    private $userId;
    
    private static $knowledgeBase = null;
    private static $learnedPatterns = [];
    private static $cropList = null;
    private static $stopWords = null;
    
    public function __construct() {
        $this->db = Database::getInstance();
        $this->openaiApiKey = $_ENV['OPENAI_API_KEY'] ?? '';
        $this->model = $_ENV['OPENAI_MODEL'] ?? 'gpt-3.5-turbo';
        
        // Load learned patterns from database
        $this->loadLearnedPatterns();
        $this->loadCropList();
        $this->loadStopWords();
    }
    
    /**
     * Main method to get AI response
     */
    public function getResponse($message, $userId, $context = [], $sessionId = null) {
        try {
            $this->userId = $userId;
            
            // Validate input
            if (empty($message)) {
                throw new \Exception('Message cannot be empty');
            }
            
            if (strlen($message) > 2000) {
                throw new \Exception('Message too long. Maximum 2000 characters.');
            }
            
            // Generate or use existing session ID
            if (empty($sessionId)) {
                $sessionId = $this->generateSessionId($userId);
            }
            
            // Detect language
            $language = $this->detectLanguage($message);
            
            // Get time-aware greeting
            $timeGreeting = $this->getTimeBasedGreeting($language);
            
            // Get conversation history for context
            $conversationHistory = $this->getSessionHistory($sessionId, 5);
            
            // Enhance context with user profile data
            $enrichedContext = $this->enrichContext($userId, $context);
            
            // Check for special patterns (greetings, thanks, etc.)
            $specialResponse = $this->handleSpecialPatterns($message, $language, $timeGreeting);
            if ($specialResponse) {
                $this->saveConversation($userId, $sessionId, $message, $specialResponse, $language, 'pattern_match');
                return [
                    'success' => true,
                    'response' => $specialResponse,
                    'language' => $language,
                    'source' => 'pattern_match',
                    'session_id' => $sessionId,
                    'timestamp' => date('Y-m-d H:i:s')
                ];
            }
            
            // Classify the query for intelligent routing
            $classification = $this->classifyQuery($message, $language);
            
            // Try multi-source knowledge retrieval with classification
            $knowledgeResponse = $this->getMultiSourceKnowledge($message, $language, $enrichedContext, $classification);
            
            if ($knowledgeResponse) {
                // Enhance with context awareness
                $enhancedResponse = $this->getContextAwareResponse($message, $language, $enrichedContext, $classification);
                $response = $enhancedResponse . $knowledgeResponse;
                $source = 'knowledge_base';
            } else {
                // For development, always use enhanced rule-based system
                $response = $this->getEnhancedRuleBasedResponse(
                    $message, 
                    $language, 
                    $enrichedContext, 
                    $conversationHistory,
                    $classification
                );
                $source = 'enhanced_rules';
                
                // Add development mode note
                if ($_ENV['APP_ENV'] === 'development') {
                    $response .= "\n\n*Development Mode - Using local knowledge base*";
                }
            }
            
            // Save conversation with classification data
            $this->saveConversation($userId, $sessionId, $message, $response, $language, $source);
            
            // Update user interaction statistics
            $this->updateUserStats($userId, $language);
            
            return [
                'success' => true,
                'response' => $response,
                'language' => $language,
                'source' => $source,
                'session_id' => $sessionId,
                'timestamp' => date('Y-m-d H:i:s'),
                'context_used' => !empty($enrichedContext),
                'classification' => $classification
            ];
            
        } catch (\Exception $e) {
            error_log('AI Assistant Error: ' . $e->getMessage());
            
            // Always return success with a helpful message
            return [
                'success' => true, // Changed from false to true for better UX
                'message' => 'Using local knowledge base',
                'response' => $this->getEnhancedRuleBasedResponse($message ?? '', $language ?? 'en', [], [], []),
                'language' => $language ?? 'en',
                'source' => 'local',
                'session_id' => $sessionId ?? null,
                'timestamp' => date('Y-m-d H:i:s')
            ];
        }
    }
    
    /**
     * Classify user query for intelligent routing
     */
    private function classifyQuery($message, $language) {
        $messageLower = mb_strtolower(trim($message), 'UTF-8');
        
        $classification = [
            'type' => 'general',
            'crop' => null,
            'topic' => null,
            'subtopic' => null,
            'urgency' => 'normal',
            'language' => $language,
            'confidence' => 1.0
        ];
        
        // Detect specific crop
        $classification['crop'] = $this->detectCrop($messageLower, $language);
        
        // Detect main topic
        $classification['topic'] = $this->detectTopic($messageLower, $language);
        
        // Detect subtopic
        $classification['subtopic'] = $this->detectSubtopic($messageLower, $language);
        
        // Detect urgency
        $classification['urgency'] = $this->detectUrgency($messageLower, $language);
        
        // Determine query type based on classification
        if ($classification['crop'] && $classification['topic']) {
            $classification['type'] = 'specific';
        } elseif ($classification['topic'] && !$classification['crop']) {
            $classification['type'] = 'general_topic';
        }
        
        return $classification;
    }
    
    /**
     * Detect specific crop in message
     */
    private function detectCrop($message, $language) {
        $crops = $this->getCropList($language);
        
        foreach ($crops as $crop => $aliases) {
            foreach ($aliases as $alias) {
                if (strpos($message, $alias) !== false) {
                    return $crop;
                }
            }
        }
        
        return null;
    }
    
    /**
     * Get crop list for language
     */
    private function getCropList($language) {
        return [
            'en' => [
                'tomato' => ['tomato', 'tomatoes'],
                'maize' => ['maize', 'corn'],
                'beans' => ['beans'],
                'cassava' => ['cassava'],
                'cabbage' => ['cabbage'],
                'coffee' => ['coffee'],
                'potato' => ['potato', 'sweet potato'],
                'onion' => ['onion'],
                'banana' => ['banana'],
                'sugarcane' => ['sugarcane', 'sugar cane']
            ],
            'lusoga' => [
                'tomato' => ['nyaanya'],
                'maize' => ['kasooli', 'maize'],
                'beans' => ['bikooge'],
                'cassava' => ['muwogo'],
                'cabbage' => ['nakati'],
                'coffee' => ['emmwanyi'],
                'potato' => ['lumonde'],
                'onion' => ['katungulu'],
                'banana' => ['ndizi'],
                'sugarcane' => ['enkoko']
            ]
        ][$language] ?? [];
    }
    
    /**
     * Detect main topic in message
     */
    private function detectTopic($message, $language) {
        $topics = [
            'en' => [
                'disease' => ['disease', 'sick', 'illness', 'infected', 'infection', 'symptom'],
                'pest' => ['pest', 'insect', 'bug', 'worm', 'caterpillar', 'aphid', 'beetle'],
                'growing' => ['grow', 'plant', 'cultivate', 'planting', 'growing', 'cultivation'],
                'schedule' => ['when', 'time', 'season', 'schedule', 'calendar', 'month'],
                'price' => ['price', 'cost', 'sell', 'buy', 'market', 'value', 'costing'],
                'fertilizer' => ['fertilizer', 'manure', 'nutrient', 'fertilize', 'dap', 'urea', 'npk'],
                'soil' => ['soil', 'earth', 'dirt', 'land', 'ground', 'fertility'],
                'water' => ['water', 'irrigation', 'rain', 'drought', 'dry', 'moisture'],
                'harvest' => ['harvest', 'harvesting', 'yield', 'produce', 'output'],
                'storage' => ['store', 'storage', 'preserve', 'keep', 'save']
            ],
            'lusoga' => [
                'disease' => ['bulwadhe', 'kufa', 'obulwadhe', 'obulema'],
                'pest' => ['ebiwuka', 'enjooka', 'ebinyonyi', 'ebikoko'],
                'growing' => ['okulima', 'okusimba', 'okukula', 'okusimba'],
                'schedule' => ['dijja', 'obudde', 'essaawa', 'omwezi', 'emyaka'],
                'price' => ['emiwendo', 'okutunda', 'okugula', 'bbanja'],
                'fertilizer' => ['okuzuukusa', 'fertilizer', 'obusa', 'amafuta'],
                'soil' => ['ettaka', 'ensi', 'obugimu'],
                'water' => ['amazzi', 'enkuba', 'okusisinkana'],
                'harvest' => ['okungula', 'okuzuula', 'okusasula'],
                'storage' => ['okutereka', 'okusigala', 'okukuuma']
            ]
        ];
        
        $langTopics = $topics[$language] ?? $topics['en'];
        
        foreach ($langTopics as $topic => $keywords) {
            foreach ($keywords as $keyword) {
                if (strpos($message, $keyword) !== false) {
                    return $topic;
                }
            }
        }
        
        return null;
    }
    
    /**
     * Detect subtopic in message
     */
    private function detectSubtopic($message, $language) {
        $subtopics = [
            'en' => [
                'prevention' => ['prevent', 'avoid', 'stop', 'protect'],
                'treatment' => ['treat', 'cure', 'control', 'spray', 'medicine'],
                'identification' => ['identify', 'recognize', 'know', 'tell', 'look like'],
                'causes' => ['cause', 'reason', 'why', 'because'],
                'symptoms' => ['symptom', 'sign', 'show', 'appear'],
                'organic' => ['organic', 'natural', 'traditional', 'home'],
                'chemical' => ['chemical', 'pesticide', 'herbicide', 'fungicide']
            ],
            'lusoga' => [
                'prevention' => ['okuziyiza', 'okweyisa', 'okwewala'],
                'treatment' => ['okujjanjaba', 'eddagala', 'okufumya'],
                'identification' => ['okuzuula', 'okumanya', 'okulaba'],
                'causes' => ['ensonga', 'kubanga', 'olw\'ensonga'],
                'symptoms' => ['obubonero', 'okulabika', 'okweeka'],
                'organic' => ['obuwangwa', 'obutonde', 'omu maka'],
                'chemical' => ['eddagala', 'chemical', 'obuwuka']
            ]
        ];
        
        $langSubtopics = $subtopics[$language] ?? $subtopics['en'];
        
        foreach ($langSubtopics as $subtopic => $keywords) {
            foreach ($keywords as $keyword) {
                if (strpos($message, $keyword) !== false) {
                    return $subtopic;
                }
            }
        }
        
        return null;
    }
    
    /**
     * Detect urgency in message
     */
    private function detectUrgency($message, $language) {
        $urgentWords = [
            'en' => ['emergency', 'urgent', 'help', 'quick', 'now', 'immediately', 'asap', 'critical'],
            'lusoga' => ['mangu', 'akawungeezi', 'kizibu', 'bulungi', 'nsanyuse']
        ];
        
        $langUrgent = $urgentWords[$language] ?? $urgentWords['en'];
        
        foreach ($langUrgent as $word) {
            if (strpos($message, $word) !== false) {
                return 'urgent';
            }
        }
        
        return 'normal';
    }
    
    /**
     * Get multi-source knowledge with intelligent routing
     */
    private function getMultiSourceKnowledge($message, $language, $context, $classification) {
        $messageLower = mb_strtolower($message, 'UTF-8');
        
        // 1. Check learned patterns first (exact matches)
        $learnedResponse = $this->checkLearnedPatterns($messageLower, $language);
        if ($learnedResponse) {
            return $learnedResponse;
        }
        
        // 2. Route based on classification
        if ($classification['type'] === 'specific' && $classification['crop'] && $classification['topic']) {
            // Specific crop + topic query
            return $this->handleSpecificQuery($classification, $language, $context);
        } elseif ($classification['type'] === 'general_topic' && $classification['topic']) {
            // General topic query
            return $this->handleGeneralTopicQuery($message, $classification, $language, $context);
        } else {
            // General query
            return $this->handleGeneralQuery($message, $language, $context);
        }
    }
    
    /**
     * Handle specific crop + topic queries
     */
    private function handleSpecificQuery($classification, $language, $context) {
        $crop = $classification['crop'];
        $topic = $classification['topic'];
        $subtopic = $classification['subtopic'];
        
        // Try to get information from database
        $response = $this->searchDatabaseForCropInfo($crop, $topic, $subtopic, $language);
        if ($response) {
            return $response;
        }
        
        // Try knowledge base
        $knowledgeBase = $this->getKnowledgeBase($language);
        $query = $crop . ' ' . $topic;
        $messageLower = mb_strtolower($query, 'UTF-8');
        
        foreach ($knowledgeBase as $pattern => $response) {
            if (preg_match($pattern, $messageLower)) {
                return $this->personalizeResponse($response, $context, $language);
            }
        }
        
        return null;
    }
    
    /**
     * Search database for crop information
     */
    private function searchDatabaseForCropInfo($crop, $topic, $subtopic, $language) {
        try {
            // First, try agricultural tips
            $sql = "SELECT * FROM agricultural_tips 
                    WHERE language = ? AND is_published = 1 
                    AND (crop_type LIKE ? OR title LIKE ? OR content LIKE ?)
                    ORDER BY created_at DESC LIMIT 3";
            
            $tips = $this->db->fetchAll($sql, [$language, "%{$crop}%", "%{$crop}%", "%{$crop}%"]);
            
            if (!empty($tips)) {
                return $this->formatAgriculturalTips($tips, $language);
            }
            
            // Try crop diseases
            $sql = "SELECT * FROM crop_diseases 
                    WHERE language = ? AND is_published = 1 
                    AND crop_type LIKE ?
                    ORDER BY created_at DESC LIMIT 3";
            
            $diseases = $this->db->fetchAll($sql, [$language, "%{$crop}%"]);
            
            if (!empty($diseases)) {
                return $this->formatCropDiseases($diseases, $language, $subtopic);
            }
            
            return null;
            
        } catch (\Exception $e) {
            error_log('Database search error: ' . $e->getMessage());
            return null;
        }
    }
    
    /**
     * Handle general topic queries
     */
    private function handleGeneralTopicQuery($message, $classification, $language, $context) {
        $topic = $classification['topic'];
        
        // Try knowledge base first
        $knowledgeBase = $this->getKnowledgeBase($language);
        $messageLower = mb_strtolower($message, 'UTF-8');
        
        foreach ($knowledgeBase as $pattern => $response) {
            if (preg_match($pattern, $messageLower)) {
                return $this->personalizeResponse($response, $context, $language);
            }
        }
        
        return null;
    }
    
    /**
     * Handle general queries
     */
    private function handleGeneralQuery($message, $language, $context) {
        // Try knowledge base
        $knowledgeBase = $this->getKnowledgeBase($language);
        $messageLower = mb_strtolower($message, 'UTF-8');
        
        foreach ($knowledgeBase as $pattern => $response) {
            if (preg_match($pattern, $messageLower)) {
                return $this->personalizeResponse($response, $context, $language);
            }
        }
        
        return null;
    }
    
    /**
     * Format agricultural tips response
     */
    private function formatAgriculturalTips($tips, $language) {
        if ($language === 'en') {
            $response = "**🌱 Agricultural Tips**\n\n";
        } else {
            $response = "**🌱 Amagezi g'Okulima**\n\n";
        }
        
        foreach ($tips as $tip) {
            $response .= "### " . htmlspecialchars($tip['title']) . "\n";
            
            if ($tip['crop_type']) {
                $response .= "*Crop: " . ucfirst($tip['crop_type']) . "*\n";
            }
            
            $response .= "\n" . $tip['content'] . "\n\n";
            
            $response .= "---\n\n";
        }
        
        if ($language === 'en') {
            $response .= "💡 *Source: AIMS Agricultural Knowledge Base*";
        } else {
            $response .= "💡 *Ensibuko: AIMS Eby'obulimi*";
        }
        
        return $response;
    }
    
    /**
     * Format crop diseases response
     */
    private function formatCropDiseases($diseases, $language, $subtopic = null) {
        if ($language === 'en') {
            $response = "**🦠 Crop Diseases & Pests**\n\n";
        } else {
            $response = "**🦠 Obulwadhe bw'Ebirime n'Ebiwuka**\n\n";
        }
        
        foreach ($diseases as $disease) {
            $response .= "### " . htmlspecialchars($disease['disease_name']) . "\n";
            
            $response .= "\n**" . ($language === 'en' ? 'Crop:' : 'Ekirime:') . "** " . 
                        ucfirst($disease['crop_type']) . "\n";
            
            $response .= "**" . ($language === 'en' ? 'Severity:' : 'Obuzito:') . "** " . 
                        ucfirst($disease['severity_level']) . "\n\n";
            
            if (!empty($disease['symptoms'])) {
                $response .= "**" . ($language === 'en' ? 'Symptoms:' : 'Obubonero:') . "**\n" . 
                            $disease['symptoms'] . "\n\n";
            }
            
            if (!empty($disease['treatment'])) {
                $response .= "**" . ($language === 'en' ? 'Treatment:' : 'Okujjanjaba:') . "**\n" . 
                            $disease['treatment'] . "\n\n";
            }
            
            if (!empty($disease['prevention'])) {
                $response .= "**" . ($language === 'en' ? 'Prevention:' : 'Okuziyiza:') . "**\n" . 
                            $disease['prevention'] . "\n\n";
            }
            
            $response .= "---\n\n";
        }
        
        if ($language === 'en') {
            $response .= "⚠️ *Always consult with an agricultural extension officer for proper diagnosis*";
        } else {
            $response .= "⚠️ *Bulijjo kubuuza omukulembeze w'eby'obulimi okufuna obujjanjabi obulungi*";
        }
        
        return $response;
    }
    
    /**
     * Get context-aware response prefix
     */
    private function getContextAwareResponse($message, $language, $context, $classification) {
        $response = '';
        
        if ($classification['crop'] && $classification['topic']) {
            $cropName = $this->getCropDisplayName($classification['crop'], $language);
            $topicName = $this->getTopicDisplayName($classification['topic'], $language);
            
            if ($language === 'en') {
                $response .= "## {$cropName} {$topicName} Information\n\n";
                
                if (!empty($context['location']) && $context['location'] !== 'Uganda') {
                    $response .= "*Information specific to {$context['location']} region*\n\n";
                }
                
                if ($classification['urgency'] === 'urgent') {
                    $response .= "⚠️ **Urgent Issue Detected** - Immediate attention recommended\n\n";
                }
            } else {
                $response .= "## {$cropName} {$topicName}\n\n";
                
                if (!empty($context['location']) && $context['location'] !== 'Uganda') {
                    $response .= "*Amagezi agakwatagana ne {$context['location']}*\n\n";
                }
                
                if ($classification['urgency'] === 'urgent') {
                    $response .= "⚠️ **Kizibu ekisaba okukolagana mangu**\n\n";
                }
            }
        }
        
        return $response;
    }
    
    /**
     * Get crop display name
     */
    private function getCropDisplayName($crop, $language) {
        $displayNames = [
            'tomato' => ['en' => 'Tomato', 'lusoga' => 'Nyaanya'],
            'maize' => ['en' => 'Maize', 'lusoga' => 'Kasooli'],
            'beans' => ['en' => 'Beans', 'lusoga' => 'Bikooge'],
            'cassava' => ['en' => 'Cassava', 'lusoga' => 'Muwogo'],
            'cabbage' => ['en' => 'Cabbage', 'lusoga' => 'Nakati'],
            'coffee' => ['en' => 'Coffee', 'lusoga' => 'Emmwanyi'],
            'potato' => ['en' => 'Potato', 'lusoga' => 'Lumonde'],
            'onion' => ['en' => 'Onion', 'lusoga' => 'Katungulu'],
            'banana' => ['en' => 'Banana', 'lusoga' => 'Ndizi'],
            'sugarcane' => ['en' => 'Sugarcane', 'lusoga' => 'Enkoko']
        ];
        
        return $displayNames[$crop][$language] ?? ucfirst($crop);
    }
    
    /**
     * Get topic display name
     */
    private function getTopicDisplayName($topic, $language) {
        $displayNames = [
            'en' => [
                'disease' => 'Diseases',
                'pest' => 'Pests',
                'growing' => 'Growing',
                'schedule' => 'Planting Schedule',
                'price' => 'Market Prices',
                'fertilizer' => 'Fertilizer',
                'soil' => 'Soil Management',
                'water' => 'Water Management',
                'harvest' => 'Harvesting',
                'storage' => 'Storage'
            ],
            'lusoga' => [
                'disease' => 'Obulwadhe',
                'pest' => 'Ebiwuka',
                'growing' => 'Okulima',
                'schedule' => 'Okusimba',
                'price' => 'Emiwendo',
                'fertilizer' => 'Okuzuukusa',
                'soil' => 'Ettaka',
                'water' => 'Amazzi',
                'harvest' => 'Okungula',
                'storage' => 'Okutereka'
            ]
        ];
        
        return $displayNames[$language][$topic] ?? ucfirst($topic);
    }
    
    /**
     * Load crop list from database or cache
     */
    private function loadCropList() {
        if (self::$cropList !== null) {
            return;
        }
        
        // Fallback to basic list
        self::$cropList = [
            'en' => [
                'tomato' => ['tomato'],
                'maize' => ['maize', 'corn'],
                'beans' => ['beans'],
                'cassava' => ['cassava'],
                'cabbage' => ['cabbage'],
                'coffee' => ['coffee']
            ],
            'lusoga' => [
                'tomato' => ['nyaanya'],
                'maize' => ['kasooli'],
                'beans' => ['bikooge'],
                'cassava' => ['muwogo'],
                'cabbage' => ['nakati'],
                'coffee' => ['emmwanyi']
            ]
        ];
    }
    
    /**
     * Load stop words
     */
    private function loadStopWords() {
        if (self::$stopWords !== null) {
            return;
        }
        
        self::$stopWords = [
            'general' => [
                'the', 'is', 'at', 'which', 'on', 'a', 'an', 'as', 'are', 'was', 'were',
                'how', 'what', 'when', 'where', 'why', 'can', 'could', 'would', 'should',
                'my', 'your', 'our', 'their', 'i', 'you', 'we', 'they', 'mu', 'ku', 'oba',
                'and', 'or', 'but', 'if', 'then', 'so', 'because', 'since', 'although',
                'please', 'tell', 'me', 'about', 'information', 'advice', 'help'
            ]
        ];
    }
    
    /**
     * Generate session ID
     */
    private function generateSessionId($userId) {
        return 'session_' . $userId . '_' . time() . '_' . bin2hex(random_bytes(8));
    }
    
    /**
     * Get session history
     */
    private function getSessionHistory($sessionId, $limit = 5) {
        try {
            $sql = "SELECT message, response, language 
                    FROM ai_conversations 
                    WHERE session_id = ? 
                    ORDER BY created_at DESC 
                    LIMIT ?";
            
            $history = $this->db->fetchAll($sql, [$sessionId, $limit]);
            return array_reverse($history);
            
        } catch (\Exception $e) {
            error_log('Error fetching session history: ' . $e->getMessage());
            return [];
        }
    }
    
    /**
     * Detect language
     */
    private function detectLanguage($message) {
        $lusogaPatterns = [
            'obulwadhe', 'okusimba', 'okuzuukusa', 'amasimu', 'ebirime',
            'omwezi', 'ditya', 'bwa', 'ndobulaba', 'ndisima', 'gange',
            'muwogo', 'emmere', 'okungula', 'omusaija', 'omukazi',
            'ebikoola', 'emiggo', 'ettaka', 'enkuba', 'obudde',
            'obulo', 'kasooli', 'bikooge', 'nakati', 'ensigo',
            'wasuze', 'osiibiile', 'oli otya', 'webale', 'mwebale',
            'nze', 'gwe', 'ye', 'ffe', 'mmwe', 'bo', 'ndiyinza'
        ];
        
        $messageLower = mb_strtolower($message, 'UTF-8');
        
        $matches = 0;
        foreach ($lusogaPatterns as $pattern) {
            if (mb_strpos($messageLower, $pattern) !== false) {
                $matches++;
            }
        }
        
        return $matches >= 2 ? 'lusoga' : 'en';
    }
    
    /**
     * Get time-based greeting
     */
    private function getTimeBasedGreeting($language = 'en') {
        $hour = date('G');
        
        if ($language === 'lusoga') {
            if ($hour >= 5 && $hour < 12) {
                return "Wasuze otya nno!";
            } elseif ($hour >= 12 && $hour < 17) {
                return "Osiibiile otya!";
            } elseif ($hour >= 17 && $hour < 22) {
                return "Oiwiire otya!";
            } else {
                return "Osula otya!";
            }
        } else {
            if ($hour >= 5 && $hour < 12) {
                return "Good morning!";
            } elseif ($hour >= 12 && $hour < 17) {
                return "Good afternoon!";
            } elseif ($hour >= 17 && $hour < 22) {
                return "Good evening!";
            } else {
                return "Hello!";
            }
        }
    }
    
    /**
     * Handle special patterns
     */
    private function handleSpecialPatterns($message, $language, $timeGreeting) {
        $messageLower = mb_strtolower(trim($message), 'UTF-8');
        
        // Greeting patterns
        $greetingPatterns = [
            'en' => '/^(hi|hello|hey|good morning|good afternoon|good evening|greetings|howdy|sup|wassup)$/i',
            'lusoga' => '/^(wasuze|osiibiile|oiwiire|oli otya|suubi|hello|hi)$/i'
        ];
        
        if (preg_match($greetingPatterns[$language], $messageLower)) {
            return $this->getGreetingResponse($language, $timeGreeting);
        }
        
        // Thank you patterns
        $thanksPatterns = [
            'en' => '/^(thank you|thanks|thank|thx|appreciate|grateful)$/i',
            'lusoga' => '/^(webale|mwebale|nsonyiwa|thanks)$/i'
        ];
        
        if (preg_match($thanksPatterns[$language], $messageLower)) {
            return $this->getThanksResponse($language);
        }
        
        // How are you patterns
        $howAreYouPatterns = [
            'en' => '/how are you|how do you do|how is it going|whats up/i',
            'lusoga' => '/oli otya|biriwo|osiibiile otya/i'
        ];
        
        if (preg_match($howAreYouPatterns[$language], $messageLower)) {
            return $this->getHowAreYouResponse($language);
        }
        
        return null;
    }
    
    /**
     * Get greeting response
     */
    private function getGreetingResponse($language, $timeGreeting) {
        if ($language === 'lusoga') {
            return "{$timeGreeting} 👋\n\n" .
                   "Nze **AIM AI**, omuyambi wo mu by'obulimi owa Uganda. Ndi musanyufu okukuwulira!\n\n" .
                   "**Ndiyinza okukuyamba mu:**\n" .
                   "🌱 **Obulwadhe bw'ebirime** - Okuzuula n'okujjanjaba\n" .
                   "📅 **Obudde bw'okusimba** - Okumanyi essaawa entuufu\n" .
                   "💰 **Emiwendo** - Emiwendo egiriwo kaakati\n" .
                   "🌾 **Enkola ennungi** - Amagezi g'okulima\n" .
                   "🐔 **Ebisolo** - Okufuga enkoko, ente, embuzi\n\n" .
                   "Oyagala nkuyambe mu ki? 😊";
        } else {
            return "{$timeGreeting} 👋\n\n" .
                   "I'm **AIM AI**, your intelligent agricultural assistant for Uganda. Great to connect with you!\n\n" .
                   "**I can help you with:**\n" .
                   "🌱 **Crop Diseases** - Identify and treat problems\n" .
                   "📅 **Planting Schedules** - Best times to plant\n" .
                   "💰 **Market Prices** - Current prices and trends\n" .
                   "🌾 **Best Practices** - Modern farming techniques\n" .
                   "🐔 **Livestock Care** - Poultry, cattle, goats\n\n" .
                   "What would you like to know today? 😊";
        }
    }
    
    /**
     * Get thanks response
     */
    private function getThanksResponse($language) {
        if ($language === 'lusoga') {
            return "Webale nyo! 😊\n\n" .
                   "Ndi musanyufu okukuyamba. Ndi wano buli kaseera singa oyagala okumbuuza ekirungi ekirala!\n\n" .
                   "**Jjukira:**\n" .
                   "✅ Kebera ebirime byo buli kaseera\n" .
                   "✅ Kozesa AIMS marketplace okutunda\n" .
                   "✅ Teekawo alerts za miwendo\n" .
                   "✅ Yingira mu bibiina by'abalimi\n\n" .
                   "Kabisaana mu by'obulimi! 🌾🚜";
        } else {
            return "You're very welcome! 😊\n\n" .
                   "I'm happy to help. Feel free to ask me anything else about farming!\n\n" .
                   "**Quick Tips:**\n" .
                   "✅ Monitor your crops regularly\n" .
                   "✅ Use AIMS marketplace to sell\n" .
                   "✅ Set price alerts\n" .
                   "✅ Join farmer groups\n\n" .
                   "Happy farming! 🌾🚜";
        }
    }
    
    /**
     * Get how are you response
     */
    private function getHowAreYouResponse($language) {
        if ($language === 'lusoga') {
            return "Ndi bulungi nnyo, webale okubuuza! 😊\n\n" .
                   "Ndi mwetegefu okuyamba abalimi nga ggwe okufuna omukisa mu bulimi!\n\n" .
                   "**Oyinza okumbuuza ku:**\n" .
                   "- Obulwadhe bw'ebirime\n" .
                   "- Obudde bw'okusimba\n" .
                   "- Emiwendo mu bbabali\n" .
                   "- Okuddukanya omusimu\n\n" .
                   "Mbuuza kyonna! 🌾";
        } else {
            return "I'm doing great, thank you for asking! 😊\n\n" .
                   "I'm ready to help farmers like you succeed in agriculture!\n\n" .
                   "**You can ask me about:**\n" .
                   "- Crop diseases and pests\n" .
                   "- Planting schedules\n" .
                   "- Market prices\n" .
                   "- Farm management\n\n" .
                   "What would you like to know? 🌾";
        }
    }
    
    /**
     * Enrich context with user data
     */
    private function enrichContext($userId, $context = []) {
        try {
            // Get user profile data
            $sql = "SELECT u.*, up.*, r.region_name, d.district_name, s.subcounty_name
                    FROM users u
                    LEFT JOIN user_profiles up ON u.id = up.user_id
                    LEFT JOIN regions r ON u.region_id = r.id
                    LEFT JOIN districts d ON u.district_id = d.id
                    LEFT JOIN subcounties s ON u.subcounty_id = s.id
                    WHERE u.id = ?";
            
            $user = $this->db->fetchOne($sql, [$userId]);
            
            if ($user) {
                $context['user_name'] = $user['full_name'];
                $context['location'] = $user['district_name'] ?? 'Uganda';
                $context['region'] = $user['region_name'] ?? null;
                $context['subcounty'] = $user['subcounty_name'] ?? null;
                $context['farming_experience'] = $user['years_in_farming'] ?? 0;
                $context['farm_size'] = $user['farm_size_acres'] ?? 0;
                $context['farming_type'] = $user['farming_type'] ?? null;
                
                // Get crops from profile
                if (!empty($user['crops_grown'])) {
                    $context['current_crops'] = json_decode($user['crops_grown'], true);
                }
                
                // Get livestock from profile
                if (!empty($user['livestock_kept'])) {
                    $context['livestock'] = json_decode($user['livestock_kept'], true);
                }
            }
            
            // Get user's active enterprises
            $enterpriseSql = "SELECT e.* FROM enterprises e
                             INNER JOIN farms f ON e.farm_id = f.id
                             WHERE f.user_id = ? AND e.status != 'completed'
                             ORDER BY e.created_at DESC LIMIT 5";
            
            $enterprises = $this->db->fetchAll($enterpriseSql, [$userId]);
            if (!empty($enterprises)) {
                $context['enterprises'] = $enterprises;
            }
            
            return $context;
            
        } catch (\Exception $e) {
            error_log('Error enriching context: ' . $e->getMessage());
            return $context;
        }
    }
    
    /**
     * Check learned patterns
     */
    private function checkLearnedPatterns($message, $language) {
        if (empty(self::$learnedPatterns[$language])) {
            return null;
        }
        
        foreach (self::$learnedPatterns[$language] as $pattern) {
            $similarity = 0;
            similar_text($message, $pattern['question'], $similarity);
            
            if ($similarity > 85) { // 85% similarity threshold
                $pattern['usage_count']++;
                $this->updatePatternUsage($pattern['id']);
                return $pattern['response'];
            }
        }
        
        return null;
    }
    
    /**
     * Load learned patterns
     */
    private function loadLearnedPatterns() {
        try {
            $sql = "SELECT * FROM ai_learned_patterns 
                    WHERE is_active = 1 AND success_rate >= 0.7
                    ORDER BY usage_count DESC, success_rate DESC";
            
            $patterns = $this->db->fetchAll($sql);
            
            foreach ($patterns as $pattern) {
                $lang = $pattern['language'];
                if (!isset(self::$learnedPatterns[$lang])) {
                    self::$learnedPatterns[$lang] = [];
                }
                self::$learnedPatterns[$lang][] = $pattern;
            }
            
        } catch (\Exception $e) {
            error_log('Error loading learned patterns: ' . $e->getMessage());
        }
    }
    
    /**
     * Update pattern usage
     */
    private function updatePatternUsage($patternId) {
        try {
            $sql = "UPDATE ai_learned_patterns 
                    SET usage_count = usage_count + 1, last_used = NOW()
                    WHERE id = ?";
            $this->db->execute($sql, [$patternId]);
        } catch (\Exception $e) {
            error_log('Error updating pattern usage: ' . $e->getMessage());
        }
    }
    
    /**
     * Enhanced rule-based response with classification
     */
    private function getEnhancedRuleBasedResponse($message, $language, $context, $history, $classification) {
        $knowledgeBase = $this->getKnowledgeBase($language);
        $messageLower = mb_strtolower($message, 'UTF-8');
        
        // Check for context-specific responses
        if (!empty($context['enterprises'])) {
            $contextResponse = $this->getContextualResponse($message, $context, $language);
            if ($contextResponse) {
                return $contextResponse;
            }
        }
        
        // Use conversation history for context
        if (!empty($history)) {
            $historyResponse = $this->getHistoryAwareResponse($message, $history, $language);
            if ($historyResponse) {
                return $historyResponse;
            }
        }
        
        // Check for helpful guidance based on classification
        $helpfulGuidance = $this->getHelpfulGuidance($message, $language, $classification);
        if ($helpfulGuidance) {
            return $helpfulGuidance;
        }
        
        // Standard knowledge base search
        foreach ($knowledgeBase as $pattern => $response) {
            if (preg_match($pattern, $messageLower)) {
                return $this->personalizeResponse($response, $context, $language);
            }
        }
        
        // Default response
        return $this->getDefaultResponse($language);
    }
    
    /**
     * Get helpful guidance based on classification
     */
    private function getHelpfulGuidance($message, $language, $classification) {
        if ($classification['crop']) {
            $cropName = $this->getCropDisplayName($classification['crop'], $language);
            
            if ($language === 'en') {
                return "I can help you with information about {$cropName}!\n\n" .
                       "You can ask me about:\n" .
                       "- **Diseases and pests** affecting {$cropName}\n" .
                       "- **Best practices** for growing {$cropName}\n" .
                       "- **Planting schedules** for {$cropName}\n" .
                       "- **Market prices** for {$cropName}\n" .
                       "- **Harvesting and storage** of {$cropName}\n\n" .
                       "Try asking a specific question like:\n" .
                       "• 'What diseases affect {$cropName}?'\n" .
                       "• 'When should I plant {$cropName}?'\n" .
                       "• 'How do I grow {$cropName} organically?'";
            } else {
                return "Ndiyinza okukuyamba ku {$cropName}!\n\n" .
                       "Oyinza okumbuuza ku:\n" .
                       "- **Obulwadhe n'ebiwuka** ebikwata ku {$cropName}\n" .
                       "- **Enkola ennungi** z'okulima {$cropName}\n" .
                       "- **Obudde bw'okusimba** {$cropName}\n" .
                       "- **Emiwendo** gy'{$cropName}\n" .
                       "- **Okungula n'okutereka** {$cropName}\n\n" .
                       "Gezaako okubuuza ekirungi nga:\n" .
                       "• 'Obulwadhe ki obukwata ku {$cropName}?'\n" .
                       "• 'Dijja okusimba {$cropName}?'\n" .
                       "• 'Ndiya {$cropName} mu buwangwa?'";
            }
        }
        
        return null;
    }
    
    /**
     * Get contextual response
     */
    private function getContextualResponse($message, $context, $language) {
        $messageLower = mb_strtolower($message, 'UTF-8');
        
        // Check if asking about their own crops/enterprises
        $personalKeywords = ['my', 'mine', 'our', 'gange', 'waffe'];
        $isPersonal = false;
        
        foreach ($personalKeywords as $keyword) {
            if (stripos($message, $keyword) !== false) {
                $isPersonal = true;
                break;
            }
        }
        
        if ($isPersonal && !empty($context['enterprises'])) {
            $response = $language === 'en' ? 
                       "Based on your farm profile, here's what I found:\n\n" :
                       "Okusinziira ku farm yo, kino kye nzudde:\n\n";
            
            foreach ($context['enterprises'] as $enterprise) {
                $response .= "**" . ucfirst(str_replace('_', ' ', $enterprise['enterprise_type'])) . "**\n";
                $response .= ($language === 'en' ? "Status: " : "Embeera: ") . 
                            ucfirst($enterprise['status']) . "\n";
                
                if ($enterprise['planting_date']) {
                    $plantingDate = date('M d, Y', strtotime($enterprise['planting_date']));
                    $response .= ($language === 'en' ? "Planted: " : "Yasimbibwa: ") . 
                                $plantingDate . "\n";
                }
                
                if ($enterprise['expected_harvest_date']) {
                    $harvestDate = date('M d, Y', strtotime($enterprise['expected_harvest_date']));
                    $daysUntil = ceil((strtotime($enterprise['expected_harvest_date']) - time()) / 86400);
                    
                    if ($daysUntil > 0) {
                        $response .= ($language === 'en' ? "Harvest in: " : "Okungula mu: ") . 
                                    $daysUntil . ($language === 'en' ? " days" : " ennaku") . "\n";
                    }
                }
                
                $response .= "\n";
            }
            
            // Add relevant advice
            $response .= $this->getEnterpriseAdvice($context['enterprises'], $language);
            
            return $response;
        }
        
        return null;
    }
    
    /**
     * Get enterprise advice
     */
    private function getEnterpriseAdvice($enterprises, $language) {
        $advice = $language === 'en' ? "\n**Recommendations:**\n" : "\n**Amagezi:**\n";
        
        foreach ($enterprises as $enterprise) {
            $type = $enterprise['enterprise_type'];
            
            // Check if harvest is near
            if ($enterprise['expected_harvest_date']) {
                $daysUntil = ceil((strtotime($enterprise['expected_harvest_date']) - time()) / 86400);
                
                if ($daysUntil > 0 && $daysUntil <= 14) {
                    $cropName = ucfirst(str_replace('_', ' ', $type));
                    if ($language === 'en') {
                        $advice .= "- Your {$cropName} harvest is approaching in {$daysUntil} days. Start preparing storage and finding buyers.\n";
                    } else {
                        $advice .= "- {$cropName} yaago ekumpi okungulwa mu nnaku {$daysUntil}. Tandika okutegeka okutereka n'okunoonya abagula.\n";
                    }
                }
            }
        }
        
        return $advice;
    }
    
    /**
     * Get history-aware response
     */
    private function getHistoryAwareResponse($message, $history, $language) {
        // Check if user is following up on previous topic
        if (count($history) > 0) {
            $lastConversation = $history[count($history) - 1];
            $lastMessage = mb_strtolower($lastConversation['message'], 'UTF-8');
            $currentMessage = mb_strtolower($message, 'UTF-8');
            
            // Check for follow-up indicators
            $followUpIndicators = ['more', 'also', 'what about', 'and', 'ate', 'n\'ate', 'era'];
            
            foreach ($followUpIndicators as $indicator) {
                if (stripos($currentMessage, $indicator) !== false) {
                    // This might be a follow-up question
                    return $this->generateFollowUpResponse($lastMessage, $currentMessage, $language);
                }
            }
        }
        
        return null;
    }
    
    /**
     * Generate follow-up response
     */
    private function generateFollowUpResponse($previousMessage, $currentMessage, $language) {
        // Extract topic from previous message
        $topics = ['maize', 'beans', 'cassava', 'price', 'plant', 'disease', 
                   'kasooli', 'bikooge', 'muwogo', 'simba', 'bulwadhe'];
        
        $topic = null;
        foreach ($topics as $t) {
            if (stripos($previousMessage, $t) !== false) {
                $topic = $t;
                break;
            }
        }
        
        if ($topic) {
            // Search for additional information about the same topic
            $knowledgeBase = $this->getKnowledgeBase($language);
            $query = $topic . ' ' . $currentMessage;
            $messageLower = mb_strtolower($query, 'UTF-8');
            
            foreach ($knowledgeBase as $pattern => $response) {
                if (preg_match($pattern, $messageLower)) {
                    return $response;
                }
            }
        }
        
        return null;
    }
    
    /**
     * Get knowledge base
     */
    private function getKnowledgeBase($language) {
        // For now, use a simple knowledge base
        // In a real application, load from config files
        
        if ($language === 'lusoga') {
            return [
                '/bulwadhe.*kasooli/' => "**Obulwadhe bw'ekasooli:**\n\n" .
                                        "1. **Obulwadhe bwa blight**\n" .
                                        "- Obubonero: Emikoola gigwa mangu\n" .
                                        "- Okujjanjaba: Kozesa ddagala eriyita Copper fungicide\n\n" .
                                        "2. **Obulwadhe bwa rust**\n" .
                                        "- Obubonero: Emikoola gigwa ennyiriri enzirugavu\n" .
                                        "- Okuziyiza: Simba ensigo ezirungi\n\n" .
                                        "3. **Obulwadhe bwa smut**\n" .
                                        "- Obubonero: Ebikoola bigwa ebikoola ebizito\n" .
                                        "- Okujjanjaba: Gya ebirime ebimala\n\n" .
                                        "⚠️ *Buuza omukulembeze w'eby'obulimi okufuna obujjanjabi obulungi*",
                
                '/bulwadhe.*muwogo/' => "**Obulwadhe bw'emuwogo:**\n\n" .
                                       "1. **Cassava mosaic disease**\n" .
                                       "- Obubonero: Emikoola gyeewuuka\n" .
                                       "- Okuziyiza: Simba ensigo ezirungi\n\n" .
                                       "2. **Cassava brown streak**\n" .
                                       "- Obubonero: Emizira gyeewuuka\n" .
                                       "- Okuziyiza: Kebera ebirime buli kaseera\n\n" .
                                       "⚠️ *Ebikoola ebibisi biyiza okuziyiza obulwadhe*",
                
                '/emiwendo.*kasooli/' => "**Emiwendo gy'ekasooli:**\n\n" .
                                        "📍 **Mu bbabali:**\n" .
                                        "- Awooma: UGX 1,200-1,500 per kg\n" .
                                        "- Jinja: UGX 1,300-1,600 per kg\n" .
                                        "- Mbale: UGX 1,100-1,400 per kg\n\n" .
                                        "💡 **Amagezi:**\n" .
                                        "- Tunda mu kyeya (December-February)\n" .
                                        "- Kozesa AIMS marketplace okutunda\n" .
                                        "- Yingira mu bibiina by'abalimi",
                
                '/kusimba.*kasooli/' => "**Okusimba ekasooli:**\n\n" .
                                       "1. **Obudde:** Simba mu kyeya (March-May) oba mu mpewo (August-October)\n" .
                                       "2. **Enkola:** Simba mu ntebe ezikungulu\n" .
                                       "3. **Ebisaanyizo:** Teeka fertilizer za NPK (200kg/ha)\n" .
                                       "4. **Ennaku z'okungula:** 90-120 ennaku\n" .
                                       "5. **Obuwanguzi:** 3-5 tons/ha"
            ];
        } else {
            return [
                '/disease.*maize/' => "**Maize Diseases:**\n\n" .
                                     "1. **Maize Blight**\n" .
                                     "- Symptoms: Leaves die quickly\n" .
                                     "- Treatment: Use Copper fungicide\n\n" .
                                     "2. **Maize Rust**\n" .
                                     "- Symptoms: Orange streaks on leaves\n" .
                                     "- Prevention: Plant resistant varieties\n\n" .
                                     "3. **Maize Smut**\n" .
                                     "- Symptoms: Swollen kernels\n" .
                                     "- Treatment: Remove infected plants\n\n" .
                                     "⚠️ *Always consult an agricultural officer*",
                
                '/disease.*cassava/' => "**Cassava Diseases:**\n\n" .
                                       "1. **Cassava Mosaic Disease**\n" .
                                       "- Symptoms: Mottled leaves\n" .
                                       "- Prevention: Plant clean cuttings\n\n" .
                                       "2. **Cassava Brown Streak**\n" .
                                       "- Symptoms: Brown streaks on stems\n" .
                                       "- Management: Regular monitoring\n\n" .
                                       "⚠️ *Healthy planting materials prevent diseases*",
                
                '/price.*maize/' => "**Maize Market Prices:**\n\n" .
                                   "📍 **Current Prices:**\n" .
                                   "- Kampala: UGX 1,200-1,500 per kg\n" .
                                   "- Jinja: UGX 1,300-1,600 per kg\n" .
                                   "- Mbale: UGX 1,100-1,400 per kg\n\n" .
                                   "💡 **Tips:**\n" .
                                   "- Sell during dry season (December-February)\n" .
                                   "- Use AIMS marketplace to sell\n" .
                                   "- Join farmer groups",
                
                '/plant.*maize/' => "**Maize Planting Guide:**\n\n" .
                                   "1. **Timing:** Plant in rainy season (March-May) or second season (August-October)\n" .
                                   "2. **Spacing:** Plant in rows 75cm apart\n" .
                                   "3. **Fertilizer:** Apply NPK fertilizer (200kg/ha)\n" .
                                   "4. **Harvest:** 90-120 days after planting\n" .
                                   "5. **Yield:** 3-5 tons per hectare"
            ];
        }
    }
    
    /**
     * Personalize response
     */
    private function personalizeResponse($response, $context, $language) {
        // Add user name if available
        if (!empty($context['user_name'])) {
            $firstName = explode(' ', $context['user_name'])[0];
            if ($language === 'en') {
                $response = str_replace('{{name}}', $firstName, $response);
            }
        }
        
        // Add location context if relevant
        if (!empty($context['location']) && strpos($response, 'Uganda') === false) {
            $suffix = $language === 'lusoga' 
                ? "\n\n*Ebyo bigwanidde " . htmlspecialchars($context['location']) . "*"
                : "\n\n*This applies to the " . htmlspecialchars($context['location']) . " region*";
            $response .= $suffix;
        }
        
        return $response;
    }
    
    /**
     * Get default response
     */
    private function getDefaultResponse($language) {
        if ($language === 'lusoga') {
            return "Nsonyiwa, simanyi bulungi ekyo. 🤔\n\n" .
                   "Ndiyinza okukuyamba mu:\n" .
                   "- **Obulwadhe bw'ebirime** (kasooli, muwogo, bikooge)\n" .
                   "- **Okusimba n'okungula** ebirime\n" .
                   "- **Emiwendo** gy'ebintu mu bbabali\n" .
                   "- **Okuzuukusa ettaka**\n" .
                   "- **Obudde** n'okulima\n" .
                   "- **Ebisolo** (enkoko, ente, embuzi)\n\n" .
                   "Buuza ekirungi era ekirambudde! 😊";
        } else {
            return "I'm here to help with agricultural questions! 😊\n\n" .
                   "I can assist you with:\n" .
                   "- **Crop Diseases & Pests**\n" .
                   "- **Planting Schedules**\n" .
                   "- **Market Prices**\n" .
                   "- **Soil Management**\n" .
                   "- **Weather & Climate**\n" .
                   "- **Livestock Care**\n\n" .
                   "Please ask a specific question about farming! 🌾";
        }
    }
    
    /**
     * Save conversation
     */
    private function saveConversation($userId, $sessionId, $message, $response, $language, $source) {
        try {
            $sql = "INSERT INTO ai_conversations 
                    (user_id, session_id, message, response, language, source, created_at)
                    VALUES (?, ?, ?, ?, ?, ?, NOW())";
            
            $this->db->execute($sql, [
                $userId,
                $sessionId,
                $message,
                $response,
                $language,
                $source
            ]);
            
        } catch (\Exception $e) {
            error_log('Error saving AI conversation: ' . $e->getMessage());
        }
    }
    
    /**
     * Update user stats
     */
    private function updateUserStats($userId, $language) {
        try {
            $sql = "UPDATE users SET last_activity = NOW() WHERE id = ?";
            $this->db->execute($sql, [$userId]);
        } catch (\Exception $e) {
            error_log('Error updating user stats: ' . $e->getMessage());
        }
    }
    
    /**
     * Get user sessions
     */
    public function getUserSessions($userId, $limit = 20) {
        try {
            $sql = "SELECT 
                        session_id,
                        MIN(created_at) as started_at,
                        MAX(created_at) as last_message_at,
                        COUNT(*) as message_count,
                        (SELECT message FROM ai_conversations ac2 
                         WHERE ac2.session_id = ac.session_id 
                         ORDER BY created_at ASC LIMIT 1) as first_message
                    FROM ai_conversations ac
                    WHERE user_id = ?
                    GROUP BY session_id
                    ORDER BY last_message_at DESC
                    LIMIT ?";
            
            return $this->db->fetchAll($sql, [$userId, $limit]);
            
        } catch (\Exception $e) {
            error_log('Error fetching user sessions: ' . $e->getMessage());
            return [];
        }
    }
    
    /**
     * Get session messages
     */
    public function getSessionMessages($sessionId) {
        try {
            $sql = "SELECT * FROM ai_conversations 
                    WHERE session_id = ? 
                    ORDER BY created_at ASC";
            
            return $this->db->fetchAll($sql, [$sessionId]);
            
        } catch (\Exception $e) {
            error_log('Error fetching session messages: ' . $e->getMessage());
            return [];
        }
    }
    
    /**
     * Clear history
     */
    public function clearHistory($userId) {
        try {
            $sql = "DELETE FROM ai_conversations WHERE user_id = ?";
            return $this->db->execute($sql, [$userId]);
        } catch (\Exception $e) {
            error_log('Error clearing conversation history: ' . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Get stats
     */
    public function getStats($userId) {
        try {
            $sql = "SELECT 
                        COUNT(DISTINCT session_id) as total_conversations,
                        COUNT(*) as total_messages,
                        SUM(CASE WHEN language = 'lusoga' THEN 1 ELSE 0 END) as lusoga_count,
                        SUM(CASE WHEN language = 'en' THEN 1 ELSE 0 END) as english_count,
                        SUM(CASE WHEN source = 'openai' THEN 1 ELSE 0 END) as openai_count,
                        SUM(CASE WHEN source = 'rule_based' THEN 1 ELSE 0 END) as rule_based_count,
                        MIN(created_at) as first_conversation,
                        MAX(created_at) as last_conversation
                    FROM ai_conversations 
                    WHERE user_id = ?";
            
            return $this->db->fetchOne($sql, [$userId]);
            
        } catch (\Exception $e) {
            error_log('Error fetching AI stats: ' . $e->getMessage());
            return null;
        }
    }
}