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

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

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

// Ensure JSON response
header('Content-Type: application/json');

// Check authentication
if (!isLoggedIn()) {
    jsonError('Unauthorized access', 401);
}

// Check if POST request
if (!isPost()) {
    jsonError('Invalid request method');
}

try {
    // Get request data
    $message = trim($_POST['message'] ?? '');
    $userId = getUserId();
    $userType = $_POST['user_type'] ?? getUserType();
    
    // Validate message
    if (empty($message)) {
        jsonError('Message is required');
    }
    
    if (strlen($message) > 1000) {
        jsonError('Message too long. Maximum 1000 characters.');
    }
    
    // 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
    jsonSuccess('Response generated', [
        'response' => $aiResponse,
        'language' => $language,
        'timestamp' => date('Y-m-d H:i:s')
    ]);
    
} catch (Exception $e) {
    logError('AI Chat Error: ' . $e->getMessage());
    jsonError('An error occurred while processing your request');
}

/**
 * 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 [
            '/obulwadhe.*muwogo|cassava.*brown.*streak/i' => 
                "**Obulwadhe bwa Cassava Brown Streak:**\n\n" .
                "**Obubonero:**\n" .
                "- Amabala ama brown ku bikoola\n" .
                "- Emiggo gya brown mu muwogo\n" .
                "- Ebikoola bikala\n\n" .
                "**Okukozesa:**\n" .
                "- Simba emisimbe egirungi (clean planting material)\n" .
                "- Malawo ebirime ebirwadhe\n" .
                "- Simba enzigu ezitariko bulwadhe\n" .
                "- Kozesa ensigo ezirinye (improved varieties: NASE 14, NASE 19)",
            
            '/okusimba.*beans|dijja.*okusimba/i' =>
                "**Okusimba Ebikooge:**\n\n" .
                "**Obudde:**\n" .
                "- Season A: February-March\n" .
                "- Season B: August-September\n\n" .
                "**Engeri:**\n" .
                "- Spacing: 50cm wakati w'ennyiriri, 10cm mu nnyiriri\n" .
                "- Depth: 5cm mu ttaka\n" .
                "- Fertilizer: DAP wakati w'okusimba\n" .
                "- Okungula: Emyezi 3-4",
            
            '/emiwendo.*maize|price.*maize/i' =>
                "**Emiwendo ga Obulo:**\n\n" .
                "Enkola:\n" .
                "1. Londa ku **Marketplace** ku AIMS\n" .
                "2. Laba emiwendo egiriwo kaakati\n" .
                "3. Geraageranya amabeere g'abantu abalala\n\n" .
                "Ebbuyu mu Eastern Uganda kaakati: UGX 800-1,200 per kg"
        ];
    } else {
        return [
            '/maize.*rust|rust.*disease/i' =>
                "**Maize Rust Disease:**\n\n" .
                "**Symptoms:**\n" .
                "- Small, circular to elongated brown pustules on leaves\n" .
                "- Pustules appear on both upper and lower leaf surfaces\n" .
                "- Yellow to orange rust spores\n" .
                "- Severe cases: leaves dry up prematurely\n\n" .
                "**Control:**\n" .
                "- Use resistant varieties (e.g., Longe 10H, DH04)\n" .
                "- Apply fungicides (Mancozeb, Metalaxyl)\n" .
                "- Practice crop rotation\n" .
                "- Remove and destroy infected plants\n" .
                "- Ensure proper spacing for air circulation\n\n" .
                "**Prevention:**\n" .
                "- Plant during recommended season\n" .
                "- Use certified seeds\n" .
                "- Apply balanced fertilizer",
            
            '/when.*plant.*beans|beans.*planting.*season/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" .
                "- Fertilizer: DAP at planting (50kg/acre)\n" .
                "- Maturity: 65-90 days depending on variety\n\n" .
                "**Recommended Varieties:**\n" .
                "- NABE 15 (90 days)\n" .
                "- K132 (75 days)\n" .
                "- NABE 17 (85 days)",
            
            '/aphids.*control|organic.*pest.*control/i' =>
                "**Organic Aphid Control:**\n\n" .
                "**Natural Solutions:**\n\n" .
                "1. **Neem Oil Spray:**\n" .
                "   - Mix 2 tablespoons neem oil + 1 tablespoon soap in 1 liter water\n" .
                "   - Spray on affected plants early morning or evening\n\n" .
                "2. **Garlic-Chili Spray:**\n" .
                "   - Blend 5 garlic cloves + 2 hot chilies + water\n" .
                "   - Strain and spray on plants\n\n" .
                "3. **Soap Water:**\n" .
                "   - 2 tablespoons liquid soap per liter of water\n" .
                "   - Spray directly on aphids\n\n" .
                "4. **Companion Planting:**\n" .
                "   - Plant marigolds, nasturtiums near crops\n" .
                "   - These repel aphids naturally\n\n" .
                "5. **Encourage Beneficial Insects:**\n" .
                "   - Ladybugs and lacewings eat aphids\n" .
                "   - Plant flowers to attract them",
            
            '/market.*price.*maize|maize.*price/i' =>
                "**Current Maize Prices:**\n\n" .
                "To check current maize prices:\n\n" .
                "1. Visit the **Marketplace** section in AIMS\n" .
                "2. Check the **Price Comparison** page\n" .
                "3. Compare prices from different markets\n\n" .
                "**Recent Range (Eastern Uganda):**\n" .
                "- Wholesale: UGX 800-1,200 per kg\n" .
                "- Retail: UGX 1,000-1,500 per kg\n\n" .
                "**Tips for Better Prices:**\n" .
                "- Sell when prices are high (usually Dec-Feb)\n" .
                "- Ensure proper drying (moisture below 13.5%)\n" .
                "- Remove damaged grains\n" .
                "- Consider bulking with other farmers\n\n" .
                "*Prices vary by season and quality.*",
            
            '/soil.*improve|fertilizer.*recommend/i' =>
                "**Soil Improvement & Fertilizer:**\n\n" .
                "**Organic Methods:**\n" .
                "1. **Compost:**\n" .
                "   - Mix crop residues, animal manure, kitchen waste\n" .
                "   - Apply 5-10 tons per acre\n\n" .
                "2. **Animal Manure:**\n" .
                "   - Cow/goat manure: 10 tons/acre\n" .
                "   - Poultry manure: 3-5 tons/acre (higher nitrogen)\n\n" .
                "3. **Cover Crops:**\n" .
                "   - Plant legumes (beans, peas) to fix nitrogen\n" .
                "   - Plough back into soil\n\n" .
                "**Inorganic Fertilizers:**\n" .
                "1. **DAP (Diammonium Phosphate):**\n" .
                "   - At planting: 50kg/acre\n" .
                "   - High in phosphorus\n\n" .
                "2. **Urea:**\n" .
                "   - Top dressing: 50kg/acre (4-6 weeks after planting)\n" .
                "   - High in nitrogen\n\n" .
                "3. **NPK (17:17:17):**\n" .
                "   - Balanced fertilizer: 100kg/acre\n\n" .
                "**Soil Testing:**\n" .
                "- Test your soil at NARL Kawanda or district agricultural office\n" .
                "- Get specific recommendations for your farm"
        ];
    }
}

/**
 * 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
    }
}