<?php
/**
 * ============================================================================
 * ai-assistant/ajax/history.php - Get Conversation History
 * ============================================================================
 */

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

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

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

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

try {
    $userId = getUserId();
    $filter = isset($_GET['filter']) ? $_GET['filter'] : 'all';
    
    // Create AI assistant instance
    require_once __DIR__ . '/../../classes/AIAssistant.php';
    $ai = new \App\AIAssistant();
    
    // Get history
    $db = \App\Database::getInstance();
    
    $sql = "SELECT * FROM ai_conversations 
            WHERE user_id = ?";
    
    $params = [$userId];
    
    if ($filter === 'en') {
        $sql .= " AND language = 'en'";
    } elseif ($filter === 'lusoga') {
        $sql .= " AND language = 'lusoga'";
    }
    
    $sql .= " ORDER BY created_at DESC LIMIT 50";
    
    $conversations = $db->fetchAll($sql, $params);
    
    echo json_encode([
        'success' => true,
        'conversations' => $conversations
    ]);
    
} catch (Exception $e) {
    error_log('History Error: ' . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Error loading history'
    ]);
}