<?php
require_once __DIR__ . '/includes/init.php';
require_once __DIR__ . '/ai/LocalAIApi.php';

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

// Get or create a session ID
if (isset($_SESSION['chat_session_id'])) {
    $session_id = $_SESSION['chat_session_id'];
} else {
    $user_id = $_SESSION['user']['id'] ?? null;
    $client_id = $_SESSION['user']['client_id'] ?? null;
    $stmt = db()->prepare("INSERT INTO chat_sessions (user_id, client_id) VALUES (?, ?)");
    $stmt->execute([$user_id, $client_id]);
    $session_id = db()->lastInsertId();
    $_SESSION['chat_session_id'] = $session_id;
}

// Load conversation history
$stmt = db()->prepare("SELECT sender, message FROM chat_messages WHERE session_id = ? ORDER BY created_at ASC");
$stmt->execute([$session_id]);
$history = $stmt->fetchAll(PDO::FETCH_ASSOC);

function search_kb($message) {
    $terms = explode(' ', $message);
    $sql = "SELECT * FROM kb_documents WHERE is_active = 1 AND (";
    $conditions = [];
    foreach ($terms as $term) {
        $conditions[] = "title LIKE ? OR content LIKE ? OR file_content LIKE ?";
    }
    $sql .= implode(' OR ', $conditions) . ") LIMIT 3";

    $stmt = db()->prepare($sql);
    $params = [];
    foreach ($terms as $term) {
        $params[] = '%' . $term . '%';
        $params[] = '%' . $term . '%';
        $params[] = '%' . $term . '%';
    }
    $stmt->execute($params);
    return $stmt->fetchAll();
}

$input = json_decode(file_get_contents('php://input'), true);
$message = $input['message'] ?? '';

if (empty($message)) {
    echo json_encode(['reply' => 'Please enter a message.']);
    exit;
}

// Save user message
$stmt = db()->prepare("INSERT INTO chat_messages (session_id, sender, message) VALUES (?, 'user', ?)");
$stmt->execute([$session_id, $message]);

$kb_documents = search_kb($message);

$messages = [];
$system_prompt = "You are a helpful assistant for Extrading, a company that sells construction materials. Please answer in ' . ($lang ?? 'en') . ' language. Answer the user\'s questions based on the provided context. If the answer is not in the context, say you don\'t know.";

if (!empty($kb_documents)) {
    $system_prompt .= "\n\nContext from knowledge base:\n";
    foreach ($kb_documents as $doc) {
        $system_prompt .= "- Title: " . $doc['title'] . "\n";
        $system_prompt .= "  Content: " . $doc['content'] . "\n";
        if (!empty($doc['file_content'])) {
            $system_prompt .= "  File Content: " . $doc['file_content'] . "\n";
        }
    }
}

$messages[] = ['role' => 'system', 'content' => $system_prompt];

foreach ($history as $msg) {
    $messages[] = ['role' => $msg['sender'], 'content' => $msg['message']];
}

$messages[] = ['role' => 'user', 'content' => $message];

$response = LocalAIApi::createResponse([
    'input' => $messages,
]);

if (!empty($response['success'])) {
    $reply = LocalAIApi::extractText($response);
} else {
    $reply = 'Sorry, I am having trouble connecting to the AI service. Please try again later.';
    error_log('AI API Error: ' . ($response['error'] ?? 'Unknown error'));
}

// Save assistant message
$stmt = db()->prepare("INSERT INTO chat_messages (session_id, sender, message) VALUES (?, 'assistant', ?)");
$stmt->execute([$session_id, $reply]);

echo json_encode(['reply' => $reply]);
