<?php
/**
 * ============================================================================
 * ai-assistant/ajax/chat.php - Enhanced Chat Handler with Classification
 * ============================================================================
 */

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

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

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

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();
    $sessionId = isset($_POST['session_id']) ? $_POST['session_id'] : null;
    
    // Validate message
    if (empty($message)) {
        echo json_encode([
            'success' => false, 
            'message' => 'Message is required'
        ]);
        exit;
    }
    
    // Get enhanced user context
    $context = getEnhancedUserContext($userId, $userType);
    
    // Create AI assistant instance
    require_once __DIR__ . '/../../classes/AIAssistant.php';
    $ai = new \App\AIAssistant();
    
    // Get response with session context
    $result = $ai->getResponse($message, $userId, $context, $sessionId);
    
    // Log the interaction for analytics
    logAIInteraction($userId, $sessionId, $message, $result);
    
    // Return response
    echo json_encode($result);
    exit;
    
} catch (Exception $e) {
    error_log('AI Chat Error: ' . $e->getMessage());
    error_log('Stack trace: ' . $e->getTraceAsString());
    
    echo json_encode([
        'success' => false,
        'message' => 'An error occurred',
        'response' => 'Sorry, I encountered an error. Please try again.',
        'language' => 'en',
        'source' => 'error'
    ]);
    exit;
}

/**
 * Get enhanced user context
 */
function getEnhancedUserContext($userId, $userType) {
    $db = \App\Database::getInstance();
    
    $context = [
        'user_type' => $userType,
        'location' => 'Uganda',
        'region' => 'Eastern Uganda'
    ];
    
    try {
        // Get user location and 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 = $db->fetchOne($sql, [$userId]);
        
        if ($user) {
            $context['user_name'] = $user['full_name'];
            $context['location'] = $user['district_name'] ?? 'Luuka';
            $context['region'] = $user['region_name'] ?? 'Eastern Uganda';
            $context['subcounty'] = $user['subcounty_name'] ?? '';
            $context['phone'] = $user['phone_number'];
            $context['farming_experience'] = $user['years_in_farming'] ?? 0;
            $context['farm_size_acres'] = $user['farm_size_acres'] ?? 0;
            $context['farming_type'] = $user['farming_type'] ?? 'mixed';
            
            // 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 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 = $db->fetchAll($enterpriseSql, [$userId]);
        if (!empty($enterprises)) {
            $context['enterprises'] = $enterprises;
        }
        
        // Get recent products for market context
        if ($userType === 'farmer') {
            $productSql = "SELECT category, COUNT(*) as count 
                          FROM products 
                          WHERE seller_id = ? AND status = 'available'
                          GROUP BY category
                          ORDER BY count DESC LIMIT 3";
            
            $products = $db->fetchAll($productSql, [$userId]);
            if (!empty($products)) {
                $context['selling_categories'] = array_column($products, 'category');
            }
        }
        
    } catch (Exception $e) {
        error_log('Error getting user context: ' . $e->getMessage());
    }
    
    return $context;
}

/**
 * Log AI interaction for analytics
 */
function logAIInteraction($userId, $sessionId, $message, $result) {
    try {
        $db = \App\Database::getInstance();
        
        $sql = "INSERT INTO ai_interaction_log 
                (user_id, session_id, message, response_length, source, language, 
                 classification_data, created_at)
                VALUES (?, ?, ?, ?, ?, ?, ?, NOW())";
        
        $classificationData = isset($result['classification']) ? 
                             json_encode($result['classification']) : null;
        
        $responseLength = isset($result['response']) ? strlen($result['response']) : 0;
        
        $db->execute($sql, [
            $userId,
            $sessionId,
            substr($message, 0, 500),
            $responseLength,
            $result['source'] ?? 'unknown',
            $result['language'] ?? 'en',
            $classificationData
        ]);
        
    } catch (Exception $e) {
        error_log('Error logging AI interaction: ' . $e->getMessage());
    }
}