<?php
/**
 * ============================================================================
 * ai-assistant/ajax/chat.php - Improved Session-aware Chat Handler
 * ============================================================================
 */

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 user context
    $context = getUserContext($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);
    
    // 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 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 and profile data
        $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['user_name'] = $user['full_name'];
            $context['location'] = $user['district_name'] ?? 'Luuka';
            $context['subcounty'] = $user['subcounty_name'] ?? '';
            $context['phone'] = $user['phone_number'];
        }
        
        // Get active crops for farmers
        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', 'harvesting')
                    LIMIT 5";
            $crops = $db->fetchAll($sql, [$userId]);
            
            if (!empty($crops)) {
                $context['current_crops'] = array_column($crops, 'enterprise_type');
            }
        }
        
    } catch (Exception $e) {
        error_log('Error getting user context: ' . $e->getMessage());
    }
    
    return $context;
}