<?php
/**
 * ============================================================================
 * ai-assistant/ajax/chat.php - AI Chat Backend
 * ============================================================================
 */

// Start output buffering to prevent any output before JSON
ob_start();

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

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

// Clear any previous output
ob_end_clean();

// Ensure JSON response
header('Content-Type: application/json; charset=utf-8');

// Check authentication
if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

// Check if POST request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

try {
    // Get request data
    $message = isset($_POST['message']) ? trim($_POST['message']) : '';
    $userId = getUserId();
    $userType = isset($_POST['user_type']) ? $_POST['user_type'] : getUserType();
    
    // Validate message
    if (empty($message)) {
        echo json_encode(['success' => false, 'message' => 'Message is required']);
        exit;
    }
    
    if (strlen($message) > 1000) {
        echo json_encode(['success' => false, 'message' => 'Message too long. Maximum 1000 characters.']);
        exit;
    }
    
    // Detect language
    $language = detectLanguage($message);
    
    // Get user context
    $userContext = getUserContext($userId, $userType);
    
    // Generate AI response
    $aiResponse = generateAIResponse($message, $language, $userContext);
    
    // Save conversation to database
    saveConversation($userId, $message, $aiResponse, $language);
    
    // Return response
    echo json_encode([
        'success' => true,
        'message' => 'Response generated',
        'response' => $aiResponse,
        'language' => $language,
        'timestamp' => date('Y-m-d H:i:s')
    ]);
    exit;
    
} catch (Exception $e) {
    error_log('AI Chat Error: ' . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'An error occurred: ' . $e->getMessage()
    ]);
    exit;
}

/**
 * Detect if message is in Lusoga or English
 */
function detectLanguage($message) {
    // Common Lusoga words/patterns
    $lusogaPatterns = [
        'obulwadhe', 'okuzuukusa', 'amasimu', 'omwezi', 'ditya', 
        'bwa', 'ndobulaba', 'ndisima', 'gange', 'muwogo',
        'emmere', 'ebirime', 'okusimba', 'okungula', 'omusaija'
    ];
    
    $messageLower = strtolower($message);
    
    foreach ($lusogaPatterns as $pattern) {
        if (strpos($messageLower, $pattern) !== false) {
            return 'lusoga';
        }
    }
    
    return 'en';
}

/**
 * Get user context for personalized responses
 */
function getUserContext($userId, $userType) {
    $db = \App\Database::getInstance();
    
    $context = [
        'user_type' => $userType,
        'location' => 'Uganda',
        'region' => 'Eastern Uganda'
    ];
    
    try {
        // Get user location details
        $sql = "SELECT u.*, d.district_name, s.subcounty_name 
                FROM users u
                LEFT JOIN districts d ON u.district_id = d.id
                LEFT JOIN subcounties s ON u.subcounty_id = s.id
                WHERE u.id = ?";
        $user = $db->fetchOne($sql, [$userId]);
        
        if ($user) {
            $context['location'] = $user['district_name'] ?? 'Uganda';
            $context['subcounty'] = $user['subcounty_name'] ?? '';
        }
        
        // Get user's crops/enterprises if farmer
        if ($userType === 'farmer') {
            $sql = "SELECT DISTINCT e.enterprise_type 
                    FROM enterprises e
                    INNER JOIN farms f ON e.farm_id = f.id
                    WHERE f.user_id = ? AND e.status IN ('planted', 'growing')
                    LIMIT 5";
            $crops = $db->fetchAll($sql, [$userId]);
            
            if (!empty($crops)) {
                $context['current_crops'] = array_column($crops, 'enterprise_type');
            }
        }
        
    } catch (Exception $e) {
        logError('Error getting user context: ' . $e->getMessage());
    }
    
    return $context;
}

/**
 * Generate AI response using OpenAI or fallback
 */
function generateAIResponse($message, $language, $userContext) {
    // Check if OpenAI API key is configured
    if (!empty(OPENAI_API_KEY) && OPENAI_API_KEY !== 'your_openai_api_key') {
        try {
            return generateOpenAIResponse($message, $language, $userContext);
        } catch (Exception $e) {
            logError('OpenAI API Error: ' . $e->getMessage());
            // Fall through to rule-based system
        }
    }
    
    // Fallback to rule-based responses
    return generateRuleBasedResponse($message, $language, $userContext);
}

/**
 * Generate response using OpenAI API
 */
function generateOpenAIResponse($message, $language, $userContext) {
    $apiKey = OPENAI_API_KEY;
    $model = OPENAI_MODEL;
    
    // Build system prompt
    $systemPrompt = buildSystemPrompt($language, $userContext);
    
    // Prepare API request
    $data = [
        'model' => $model,
        'messages' => [
            [
                'role' => 'system',
                'content' => $systemPrompt
            ],
            [
                'role' => 'user',
                'content' => $message
            ]
        ],
        'temperature' => 0.7,
        'max_tokens' => 500
    ];
    
    // Make API call
    $ch = curl_init('https://api.openai.com/v1/chat/completions');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $apiKey
    ]);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode !== 200) {
        throw new Exception('OpenAI API returned HTTP ' . $httpCode);
    }
    
    $result = json_decode($response, true);
    
    if (!isset($result['choices'][0]['message']['content'])) {
        throw new Exception('Invalid API response format');
    }
    
    return trim($result['choices'][0]['message']['content']);
}

/**
 * Build system prompt for OpenAI
 */
function buildSystemPrompt($language, $userContext) {
    $basePrompt = "You are AIM AI, an intelligent agricultural assistant for farmers, buyers, and extension workers in Uganda, specifically in the Eastern region. ";
    
    if ($language === 'lusoga') {
        $basePrompt .= "Respond in Lusoga language. You help with:\n";
        $basePrompt .= "- Obulwadhe bw'ebirime n'obw'ebisolo (Crop and livestock diseases)\n";
        $basePrompt .= "- Okusimba n'okulima (Planting and farming practices)\n";
        $basePrompt .= "- Emiwendo y'ebintu mu bbabali (Market prices)\n";
        $basePrompt .= "- Emmere y'ettaka (Soil health)\n";
        $basePrompt .= "- Obudde (Weather advice)\n\n";
        $basePrompt .= "Waayo obwogezi obungi naye obutali buwanvu. Kozesa ebigambo ebyangudde.";
    } else {
        $basePrompt .= "You help with:\n";
        $basePrompt .= "- Crop and livestock disease identification and treatment\n";
        $basePrompt .= "- Best farming practices and planting schedules\n";
        $basePrompt .= "- Market prices and selling strategies\n";
        $basePrompt .= "- Soil health and fertilizer recommendations\n";
        $basePrompt .= "- Weather information and climate-smart agriculture\n";
        $basePrompt .= "- Pest control (organic and conventional methods)\n\n";
        $basePrompt .= "Provide practical, actionable advice suitable for Ugandan smallholder farmers. ";
        $basePrompt .= "Be concise but thorough. Use simple language.";
    }
    
    // Add user context
    if (!empty($userContext['current_crops'])) {
        $crops = implode(', ', $userContext['current_crops']);
        $basePrompt .= "\n\nUser is currently growing: " . $crops;
    }
    
    $basePrompt .= "\n\nLocation: " . $userContext['location'];
    $basePrompt .= "\nUser type: " . ucfirst($userContext['user_type']);
    
    return $basePrompt;
}

/**
 * Generate rule-based response (fallback)
 */
function generateRuleBasedResponse($message, $language, $userContext) {
    $messageLower = strtolower($message);
    
    // Load knowledge base
    $knowledgeBase = loadKnowledgeBase($language);
    
    // Try to match patterns
    foreach ($knowledgeBase as $pattern => $response) {
        if (preg_match($pattern, $messageLower)) {
            return personalizeResponse($response, $userContext, $language);
        }
    }
    
    // Default response if no match
    if ($language === 'lusoga') {
        return "Nsonyiwa, simanyi kituufu ekyo. Osobola okumbuuza ekintu ekindi ekikwata ku:\n" .
               "- Obulwadhe bw'ebirime\n" .
               "- Okusimba n'okungula\n" .
               "- Emiwendo y'ebintu\n" .
               "- Okulima okulungi\n\n" .
               "Buuza ekirungi!";
    } else {
        return "I'm here to help with agricultural questions. You can ask me about:\n" .
               "- Crop diseases and pests\n" .
               "- Planting and harvesting schedules\n" .
               "- Market prices\n" .
               "- Best farming practices\n" .
               "- Soil health and fertilizers\n\n" .
               "What would you like to know?";
    }
}

/**
 * Load knowledge base
 */
function loadKnowledgeBase($language) {
    if ($language === 'lusoga') {
        return [
            // Greetings
            '/^(wa suze|osiibiile|oli otya|osiibiile nyo|hello|hi|hey)/i' =>
                "Nsiibiile nyo! 😊\n\n" .
                "Ndi wano okukuyamba mu by'obulimi. Osobola okumbuuza ku:\n" .
                "- Obulwadhe bw'ebirime n'ebisolo\n" .
                "- Okusimba n'okungula\n" .
                "- Emiwendo y'ebintu mu bbabali\n" .
                "- Okuzuukusa ettaka\n" .
                "- Obudde n'okulima\n\n" .
                "Njagala okukuyamba! Buuza kyonna kyoagala okumanyi! 🌾",
            
            // Cassava diseases
            '/obulwadhe.*muwogo|cassava.*brown.*streak|muwogo.*bulwadhe/i' => 
                "**Obulwadhe bwa Cassava Brown Streak (CBS):**\n\n" .
                "**Obubonero:**\n" .
                "- Amabala ama brown/yellow ku bikoola\n" .
                "- Emiggo gya brown mu muwogo (inside the roots)\n" .
                "- Ebikoola bikala ne birwadha\n" .
                "- Emiggo emikalu ku bikoola\n\n" .
                "**Okukozesa:**\n" .
                "1. Simba emisimbe egirungi - clean planting material\n" .
                "2. Malawo ebirime ebirwadhe\n" .
                "3. Simba enzigu ezitariko bulwadhe\n" .
                "4. Kozesa ensigo ezirinye:\n" .
                "   - NASE 14 (resistant)\n" .
                "   - NASE 19 (tolerant)\n" .
                "   - Mkumba (resistant)\n\n" .
                "**Okuziyiza:**\n" .
                "- Simba emisimbe okuva muffield eziriko obulwadhe\n" .
                "- Weewale okusimba kumpi n'ebirime ebirwadhe\n" .
                "- Simba mu season ennungi",
            
            // Maize diseases
            '/obulwadhe.*kasooli|obulo.*bulwadhe|maize.*disease/i' =>
                "**Obulwadhe bwa Maize (Obulo):**\n\n" .
                "**1. Maize Streak Virus:**\n" .
                "- Emiggo emiteru ku bikoola\n" .
                "- Ebirime bitakula bulungi\n" .
                "- Kozesa: Ensigo eziriko obusika (resistant varieties)\n\n" .
                "**2. Maize Rust:**\n" .
                "- Amatutumba ma brown ku bikoola\n" .
                "- Kozesa eddagala: Mancozeb\n\n" .
                "**3. Fall Armyworm:**\n" .
                "- Ebiwuka birya bikoola\n" .
                "- Kozesa: Insecticide oba ash ne soap\n\n" .
                "**Ensigo ezirungi:**\n" .
                "- Longe 10H\n" .
                "- DH04\n" .
                "- Longe 5",
            
            // Planting beans
            '/okusimba.*bikooge|beans.*planting|dijja.*okusimba/i' =>
                "**Okusimba Ebikooge (Beans):**\n\n" .
                "**Obudde obwokusimba:**\n" .
                "- **Season 1:** Feb - March\n" .
                "- **Season 2:** August - September\n\n" .
                "**Engeri y'okusimba:**\n" .
                "- Spacing: 50cm (ennyiriri ne nnyiriri), 10cm (mu nnyiriri)\n" .
                "- Obuziba: 3-5cm mu ttaka\n" .
                "- Fertilizer: DAP 50kg/acre wakati w'okusimba\n\n" .
                "**Ensigo ezirungi:**\n" .
                "- NABE 15 (90 days)\n" .
                "- K132 (75 days)\n" .
                "- NABE 17 (85 days)\n\n" .
                "**Eby'okwetengerera:**\n" .
                "- Ettaka libeere dry (well-drained)\n" .
                "- Enkuba: Minimum 300mm\n" .
                "- Okungula: After 65-90 days",
            
            // Market prices
            '/emiwendo.*obulo|emiwendo.*maize|price.*kasooli/i' =>
                "**Emiwendo ga Obulo (Maize):**\n\n" .
                "Okufuna emiwendo egiriwo kaakati:\n\n" .
                "1. Londa ku **Marketplace** mu AIMS app\n" .
                "2. Laba **Price Comparison** page\n" .
                "3. Geraageranya emiwendo okuva mu mabeere g'abantu abalala\n\n" .
                "**Emiwendo mu Eastern Uganda (estimate):**\n" .
                "- Wholesale: UGX 800-1,200 per kg\n" .
                "- Retail: UGX 1,000-1,500 per kg\n\n" .
                "**Amagezi g'okutunda:**\n" .
                "- Tunda nga emiwendo giri waggulu (Dec-Feb)\n" .
                "- Kala obulo obulungi (moisture <13.5%)\n" .
                "- Ggyawo obulo obwonoonese\n" .
                "- Geraageranya okwegatta n'abalimi abalala\n\n" .
                "*Emiwendo gikyuka nga season n'omutindo*",
            
            // Soil improvement
            '/okuzuukusa.*ettaka|ettaka.*fertilizer/i' =>
                "**Okuzuukusa Ettaka:**\n\n" .
                "**Engeri z'obuwangwa:**\n" .
                "1. **Compost:**\n" .
                "   - Tabula ebisigadde by'ebirime, obusa, ebiva mu ffumbiro\n" .
                "   - Teeka 5-10 tonnes per acre\n\n" .
                "2. **Obusa bw'ebisolo:**\n" .
                "   - Ente/embuzi: 10 tonnes/acre\n" .
                "   - Enkoko: 3-5 tonnes/acre\n\n" .
                "3. **Cover Crops:**\n" .
                "   - Simba ebinyeebwa (beans, peas)\n" .
                "   - Birimu nitrogen\n\n" .
                "**Fertilizer:**\n" .
                "1. **DAP:** 50kg/acre wakati w'okusimba\n" .
                "2. **Urea:** 50kg/acre (top dressing after 4-6 weeks)\n" .
                "3. **NPK (17:17:17):** 100kg/acre\n\n" .
                "**Okugezesa ettaka:**\n" .
                "Genda ku NARL Kawanda oba district agric office",
            
            // Weather/farming tips
            '/obudde|emmeru|season/i' =>
                "**Obudde n'Okulima:**\n\n" .
                "**Seasons mu Uganda:**\n" .
                "- **Season 1:** March-May (Long rains)\n" .
                "- **Season 2:** Sept-Nov (Short rains)\n\n" .
                "**Amagezi:**\n" .
                "- Weraba enkuba nga tenabanga kusimba\n" .
                "- Simba nga ettaka liriko obunnyogovu\n" .
                "- Kozesa ensigo eziriko obusika ku kyeya\n\n" .
                "Okufuna weather forecast, laba ku **Weather** section mu AIMS app! 🌤️",
                
            // Thank you
            '/webale|mwebale|thank/i' =>
                "Webale nyo! 😊 Ndi wano buli kiseera okukuyamba. Osobola okumbuuza ekirala kyonna! 🌾"
        ];
    } else {
        return [
            // Greetings
            '/^(hello|hi|hey|good morning|good afternoon|good evening|greetings)/i' =>
                "Hello! 👋 Great to hear from you!\n\n" .
                "I'm AIM AI, your agricultural assistant. I can help you with:\n\n" .
                "🌱 **Crop Management:**\n" .
                "- Disease identification and treatment\n" .
                "- Pest control methods\n" .
                "- Planting schedules\n\n" .
                "💰 **Market Information:**\n" .
                "- Current prices\n" .
                "- Selling strategies\n\n" .
                "🌾 **Farming Practices:**\n" .
                "- Soil health\n" .
                "- Fertilizer recommendations\n" .
                "- Best varieties\n\n" .
                "What would you like to know? Ask me anything! 🚜",
            
            // How are you
            '/how are you|how do you do|whats up|wassup/i' =>
                "I'm doing great, thank you! 😊\n\n" .
                "I'm here and ready to help you with any agricultural questions. " .
                "Whether it's about crops, livestock, market prices, or farming techniques - just ask!\n\n" .
                "What farming challenge can I help you solve today? 🌾",
            
            // Maize rust disease
            '/maize.*rust|rust.*disease|rust.*maize/i' =>
                "**Maize Rust Disease:**\n\n" .
                "**Symptoms:**\n" .
                "- Small, circular to elongated brown pustules on leaves\n" .
                "- Pustules on both upper and lower leaf surfaces\n" .
                "- Yellow to orange rust spores\n" .
                "- Severe cases: premature leaf drying\n\n" .
                "**Control Methods:**\n" .
                "1. **Chemical Control:**\n" .
                "   - Apply Mancozeb or Metalaxyl fungicide\n" .
                "   - Spray when disease first appears\n" .
                "   - Repeat every 14 days if needed\n\n" .
                "2. **Cultural Practices:**\n" .
                "   - Use resistant varieties (Longe 10H, DH04)\n" .
                "   - Practice crop rotation\n" .
                "   - Remove and destroy infected plants\n" .
                "   - Ensure proper spacing (75cm x 30cm)\n\n" .
                "3. **Prevention:**\n" .
                "   - Plant during recommended season\n" .
                "   - Use certified seeds\n" .
                "   - Apply balanced fertilizer (NPK)\n" .
                "   - Avoid overhead irrigation\n\n" .
                "**Best Resistant Varieties:**\n" .
                "- Longe 10H\n" .
                "- DH04\n" .
                "- Longe 5",
            
            // Fall armyworm
            '/fall.*armyworm|armyworm|worm.*maize/i' =>
                "**Fall Armyworm Control:**\n\n" .
                "**Identification:**\n" .
                "- Green/brown caterpillars with stripes\n" .
                "- White inverted Y on head\n" .
                "- Feed on leaves, creating holes\n" .
                "- Hide in leaf whorls during day\n\n" .
                "**Control Methods:**\n\n" .
                "**1. Manual/Mechanical:**\n" .
                "- Hand-pick larvae early morning\n" .
                "- Drop in soapy water to kill\n" .
                "- Check plants daily\n\n" .
                "**2. Biological:**\n" .
                "- Release natural enemies (wasps, beetles)\n" .
                "- Use Bt (Bacillus thuringiensis)\n\n" .
                "**3. Chemical:**\n" .
                "- Emamectin benzoate\n" .
                "- Chlorantraniliprole\n" .
                "- Spray early morning or evening\n\n" .
                "**4. Home Remedies:**\n" .
                "- Ash + soap solution (spray in whorl)\n" .
                "- Neem oil spray\n" .
                "- Garlic-chili mixture\n\n" .
                "**Prevention:**\n" .
                "- Early planting\n" .
                "- Use resistant varieties\n" .
                "- Intercrop with beans or groundnuts",
            
            // Bean planting
            '/when.*plant.*beans|beans.*planting.*season|bean.*schedule/i' =>
                "**Bean Planting in Uganda:**\n\n" .
                "**Best Planting Times:**\n" .
                "- **First Season:** February - March\n" .
                "- **Second Season:** August - September\n\n" .
                "**Requirements:**\n" .
                "- Rainfall: Minimum 300mm during growing season\n" .
                "- Temperature: 18-24°C optimal\n" .
                "- Soil: Well-drained, pH 6.0-7.5\n\n" .
                "**Planting Guide:**\n" .
                "- **Spacing:** 50cm between rows, 10cm within row\n" .
                "- **Depth:** 3-5cm\n" .
                "- **Seed rate:** 40-50kg per acre\n" .
                "- **Fertilizer:** DAP at planting (50kg/acre)\n" .
                "- **Maturity:** 65-90 days depending on variety\n\n" .
                "**Recommended Varieties:**\n" .
                "- **NABE 15:** 90 days, high yielding\n" .
                "- **K132:** 75 days, disease resistant\n" .
                "- **NABE 17:** 85 days, drought tolerant\n" .
                "- **NABE 16:** 90 days, good market value\n\n" .
                "**Management Tips:**\n" .
                "- Weed 2-3 times during season\n" .
                "- Top dress with Urea at flowering\n" .
                "- Watch for aphids and bean fly\n" .
                "- Harvest when 90% pods are dry",
            
            // Aphids control
            '/aphids.*control|organic.*pest.*control|natural.*pest/i' =>
                "**Organic Aphid Control Methods:**\n\n" .
                "**1. Neem Oil Spray:**\n" .
                "- Mix 2 tablespoons neem oil + 1 tbsp liquid soap in 1 liter water\n" .
                "- Spray on affected plants early morning or evening\n" .
                "- Repeat every 3-5 days\n\n" .
                "**2. Garlic-Chili Spray:**\n" .
                "- Blend 5 garlic cloves + 2 hot chilies + 1 liter water\n" .
                "- Let sit overnight\n" .
                "- Strain and spray on plants\n" .
                "- Repeat weekly\n\n" .
                "**3. Soap Water Solution:**\n" .
                "- 2 tablespoons liquid soap per liter water\n" .
                "- Spray directly on aphids\n" .
                "- Rinse plants after 2-3 hours\n\n" .
                "**4. Wood Ash:**\n" .
                "- Sprinkle dry wood ash around plants\n" .
                "- Creates barrier aphids won't cross\n\n" .
                "**5. Companion Planting:**\n" .
                "- Plant marigolds, nasturtiums near crops\n" .
                "- These repel aphids naturally\n" .
                "- Garlic and onions also work\n\n" .
                "**6. Beneficial Insects:**\n" .
                "- Encourage ladybugs (eat 50+ aphids/day)\n" .
                "- Plant flowers to attract lacewings\n" .
                "- Don't use harsh pesticides\n\n" .
                "**7. Water Spray:**\n" .
                "- Strong water spray dislodges aphids\n" .
                "- Do early morning\n" .
                "- Repeat every 2-3 days",
            
            // Market prices
            '/market.*price.*maize|maize.*price|current.*price/i' =>
                "**Current Maize Prices:**\n\n" .
                "To check **real-time** maize prices:\n\n" .
                "1. Visit the **Marketplace** section in AIMS\n" .
                "2. Go to **Price Comparison** page\n" .
                "3. Compare prices from different markets\n" .
                "4. Filter by your location\n\n" .
                "**Recent Price Range (Eastern Uganda):**\n" .
                "- **Wholesale:** UGX 800-1,200 per kg\n" .
                "- **Retail:** UGX 1,000-1,500 per kg\n" .
                "- **Premium (dried):** UGX 1,200-1,800 per kg\n\n" .
                "**Tips for Better Prices:**\n" .
                "- **Timing:** Sell Dec-Feb when prices peak\n" .
                "- **Quality:** Ensure proper drying (moisture <13.5%)\n" .
                "- **Grading:** Remove damaged/rotten grains\n" .
                "- **Bulking:** Join other farmers for better negotiation\n" .
                "- **Storage:** Use proper storage to wait for high prices\n\n" .
                "**Price Alerts:**\n" .
                "Set up price alerts in AIMS to get notified when prices reach your target! 📊\n\n" .
                "*Note: Prices vary by season, quality, and location.*",
            
            // Soil improvement
            '/soil.*improve|fertilizer.*recommend|soil.*health/i' =>
                "**Soil Improvement & Fertilizer Guide:**\n\n" .
                "**Organic Methods:**\n\n" .
                "**1. Compost Making:**\n" .
                "- Mix: crop residues + animal manure + kitchen waste\n" .
                "- Layer brown (dry) and green (fresh) materials\n" .
                "- Keep moist, turn weekly\n" .
                "- Ready in 2-3 months\n" .
                "- Apply: 5-10 tons/acre\n\n" .
                "**2. Animal Manure:**\n" .
                "- **Cow/Goat:** 10 tons/acre\n" .
                "- **Poultry:** 3-5 tons/acre (higher nitrogen)\n" .
                "- **Pig:** 8 tons/acre\n" .
                "- Apply 2-3 weeks before planting\n\n" .
                "**3. Green Manure (Cover Crops):**\n" .
                "- Plant legumes: beans, peas, mucuna\n" .
                "- They fix nitrogen from air\n" .
                "- Plow back into soil before flowering\n\n" .
                "**4. Mulching:**\n" .
                "- Use grass, leaves, crop residues\n" .
                "- Retains moisture, adds organic matter\n" .
                "- Apply 5-10cm thick layer\n\n" .
                "**Inorganic Fertilizers:**\n\n" .
                "**1. DAP (Diammonium Phosphate):**\n" .
                "- **When:** At planting\n" .
                "- **Rate:** 50kg/acre\n" .
                "- **Nutrients:** High phosphorus (18-46-0)\n" .
                "- **Best for:** Root development, flowering\n\n" .
                "**2. Urea:**\n" .
                "- **When:** Top dressing, 4-6 weeks after planting\n" .
                "- **Rate:** 50kg/acre\n" .
                "- **Nutrients:** High nitrogen (46-0-0)\n" .
                "- **Best for:** Leafy growth, green color\n\n" .
                "**3. NPK (17:17:17):**\n" .
                "- **When:** At planting or split application\n" .
                "- **Rate:** 100kg/acre\n" .
                "- **Nutrients:** Balanced\n" .
                "- **Best for:** General crop growth\n\n" .
                "**4. CAN (Calcium Ammonium Nitrate):**\n" .
                "- **Rate:** 50kg/acre\n" .
                "- **Nutrients:** Nitrogen + Calcium\n" .
                "- **Best for:** Top dressing\n\n" .
                "**Soil Testing:**\n" .
                "- Test at NARL Kawanda or district agricultural office\n" .
                "- Cost: UGX 20,000-50,000\n" .
                "- Get specific recommendations\n\n" .
                "**Application Tips:**\n" .
                "- Apply fertilizer 5cm from plant base\n" .
                "- Cover with soil after application\n" .
                "- Apply when soil is moist\n" .
                "- Don't apply during heavy rain",
            
            // Cassava diseases
            '/cassava.*disease|cassava.*brown.*streak|mosaic.*cassava/i' =>
                "**Cassava Diseases & Control:**\n\n" .
                "**1. Cassava Brown Streak Disease (CBSD):**\n" .
                "**Symptoms:**\n" .
                "- Brown/yellow streaks on leaves\n" .
                "- Brown necrotic patches inside roots\n" .
                "- Leaf withering\n" .
                "- Stunted growth\n\n" .
                "**Control:**\n" .
                "- Use clean planting materials\n" .
                "- Plant resistant varieties:\n" .
                "  * NASE 14 (resistant)\n" .
                "  * NASE 19 (tolerant)\n" .
                "  * Mkumba (resistant)\n" .
                "- Remove and destroy infected plants\n" .
                "- Control whiteflies (vector)\n\n" .
                "**2. Cassava Mosaic Disease (CMD):**\n" .
                "**Symptoms:**\n" .
                "- Yellow/white mosaic patterns on leaves\n" .
                "- Distorted, small leaves\n" .
                "- Stunted plant growth\n" .
                "- Reduced root yield\n\n" .
                "**Control:**\n" .
                "- Use disease-free cuttings\n" .
                "- Plant resistant varieties:\n" .
                "  * NASE 1, NASE 3\n" .
                "  * TME 14\n" .
                "- Rogue out diseased plants early\n" .
                "- Control whiteflies\n\n" .
                "**3. Cassava Bacterial Blight (CBB):**\n" .
                "**Symptoms:**\n" .
                "- Water-soaked spots on leaves\n" .
                "- Wilting and die-back\n" .
                "- Gum exudation from stems\n\n" .
                "**Control:**\n" .
                "- Use healthy planting material\n" .
                "- Avoid planting in waterlogged areas\n" .
                "- Remove infected plants\n\n" .
                "**General Prevention:**\n" .
                "- Source clean planting materials\n" .
                "- Practice field sanitation\n" .
                "- Rotate crops\n" .
                "- Plant during recommended season",
            
            // Poultry farming
            '/poultry|chicken.*farming|layers|broilers/i' =>
                "**Poultry Farming Guide:**\n\n" .
                "**Types of Poultry:**\n\n" .
                "**1. Layers (Egg Production):**\n" .
                "- Start laying: 18-22 weeks\n" .
                "- Peak production: 25-30 weeks\n" .
                "- Production period: 72 weeks\n" .
                "- Feed: Layers mash/pellets\n" .
                "- Breeds: Kuroiler, KABIR, Kenbro\n\n" .
                "**2. Broilers (Meat):**\n" .
                "- Market age: 6-8 weeks\n" .
                "- Market weight: 1.5-2.5 kg\n" .
                "- Feed: Starter, Grower, Finisher\n" .
                "- Breeds: Cobb 500, Ross 308\n\n" .
                "**3. Dual Purpose:**\n" .
                "- Kuroiler, Rainbow Rooster\n" .
                "- Eggs + meat\n" .
                "- Hardy, disease resistant\n\n" .
                "**Housing Requirements:**\n" .
                "- Space: 4-5 birds per m²\n" .
                "- Ventilation: Critical!\n" .
                "- Lighting: 14-16 hours for layers\n" .
                "- Nesting boxes: 1 per 4 hens\n\n" .
                "**Feeding:**\n" .
                "- **Chicks (0-4 weeks):** Starter (23% protein)\n" .
                "- **Growers (5-20 weeks):** Grower (18% protein)\n" .
                "- **Layers:** Layer mash (16-17% protein)\n" .
                "- **Broilers:** High protein, rapid growth\n" .
                "- **Water:** Clean, always available\n\n" .
                "**Disease Prevention:**\n" .
                "- Vaccination schedule (Newcastle, Gumboro, etc.)\n" .
                "- Biosecurity measures\n" .
                "- Regular deworming\n" .
                "- Clean water and feeders daily\n\n" .
                "**Common Diseases:**\n" .
                "- Newcastle Disease\n" .
                "- Coccidiosis\n" .
                "- Fowl pox\n" .
                "- Infectious Bronchitis",
            
            // Thank you
            '/thank you|thanks|appreciate/i' =>
                "You're very welcome! 😊\n\n" .
                "I'm always here to help with your farming questions. Don't hesitate to ask anything!\n\n" .
                "Happy farming! 🌾🚜",
            
            // Help/what can you do
            '/what.*can.*you.*do|help.*me|capabilities/i' =>
                "I'm your comprehensive agricultural assistant! Here's what I can help you with:\n\n" .
                "🌱 **Crop Diseases & Pests:**\n" .
                "- Identify diseases from symptoms\n" .
                "- Recommend treatments (organic & chemical)\n" .
                "- Prevention strategies\n\n" .
                "📅 **Planting Schedules:**\n" .
                "- Best planting times for Uganda\n" .
                "- Variety recommendations\n" .
                "- Spacing and fertilizer rates\n\n" .
                "💰 **Market Intelligence:**\n" .
                "- Current crop prices\n" .
                "- Selling strategies\n" .
                "- Market trends\n\n" .
                "🌾 **Best Practices:**\n" .
                "- Soil improvement\n" .
                "- Fertilizer recommendations\n" .
                "- Water management\n" .
                "- Post-harvest handling\n\n" .
                "🐔 **Livestock:**\n" .
                "- Poultry farming\n" .
                "- Dairy management\n" .
                "- Disease control\n\n" .
                "🌤️ **Weather & Climate:**\n" .
                "- Season recommendations\n" .
                "- Climate-smart agriculture\n\n" .
                "Just ask me anything in **English** or **Lusoga**! I'm here 24/7! 🚜"
        ];
    }
}

/**
 * Personalize response based on user context
 */
function personalizeResponse($response, $userContext, $language) {
    // Add location-specific information if relevant
    if (strpos($response, 'Uganda') === false && !empty($userContext['location'])) {
        $suffix = $language === 'lusoga' 
            ? "\n\n*Ebyo bigwanidde " . $userContext['location'] . "*"
            : "\n\n*This applies to " . $userContext['location'] . " area*";
        $response .= $suffix;
    }
    
    return $response;
}

/**
 * Save conversation to database
 */
function saveConversation($userId, $message, $response, $language) {
    try {
        $db = \App\Database::getInstance();
        
        // Generate session ID if not exists
        if (!isset($_SESSION['ai_session_id'])) {
            $_SESSION['ai_session_id'] = uniqid('ai_session_', true);
        }
        
        $sql = "INSERT INTO ai_conversations 
                (user_id, session_id, message, response, language, created_at)
                VALUES (?, ?, ?, ?, ?, NOW())";
        
        $db->execute($sql, [
            $userId,
            $_SESSION['ai_session_id'],
            $message,
            $response,
            $language
        ]);
        
    } catch (Exception $e) {
        logError('Error saving conversation: ' . $e->getMessage());
        // Don't throw - conversation saving is not critical
    }
}