<?php
require_once __DIR__ . '/../db/config.php';
require_once __DIR__ . '/../ai/LocalAIApi.php';

// Get Telegram Update
$content = file_get_contents("php://input");
$update = json_decode($content, true);

if (!$update || !isset($update['message'])) {
    exit;
}

$message = $update['message'];
$chatId = $message['chat']['id'];
$text = $message['text'] ?? '';

if (empty($text)) {
    exit;
}

// Get Telegram Token from DB
$stmt = db()->query("SELECT setting_value FROM settings WHERE setting_key = 'telegram_token'");
$token = $stmt->fetchColumn();

if (!$token) {
    error_log("Telegram Error: No bot token found in settings.");
    exit;
}

function sendTelegramMessage($chatId, $text, $token) {
    $url = "https://api.telegram.org/bot$token/sendMessage";
    $data = [
        'chat_id' => $chatId,
        'text' => $text,
        'parse_mode' => 'Markdown'
    ];
    
    $options = [
        'http' => [
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',
            'content' => http_build_query($data),
        ],
    ];
    $context  = stream_context_create($options);
    return file_get_contents($url, false, $context);
}

// Process with AI (Similar logic to api/chat.php)
try {
    // 1. Fetch Knowledge Base
    $stmt = db()->query("SELECT keywords, answer FROM faqs");
    $faqs = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $knowledgeBase = "Here is the knowledge base for this website:\n\n";
    foreach ($faqs as $faq) {
        $knowledgeBase .= "Q: " . $faq['keywords'] . "\nA: " . $faq['answer'] . "\n---\n";
    }

    $systemPrompt = "You are a helpful AI assistant integrated with Telegram. " .
        "Use the provided Knowledge Base to answer user questions. " .
        "Keep answers concise for mobile reading. Use Markdown for formatting.\n\n" .
        $knowledgeBase;

    // 2. Call AI
    $response = LocalAIApi::createResponse([
        'model' => 'gpt-4o-mini',
        'input' => [
            ['role' => 'system', 'content' => $systemPrompt],
            ['role' => 'user', 'content' => $text],
        ]
    ]);

    if (!empty($response['success'])) {
        $aiReply = LocalAIApi::extractText($response);
        
        // 3. Save History
        try {
            $stmt = db()->prepare("INSERT INTO messages (user_message, ai_response) VALUES (?, ?)");
            $stmt->execute(["[Telegram] " . $text, $aiReply]);
        } catch (Exception $e) {}

        // 4. Send back to Telegram
        sendTelegramMessage($chatId, $aiReply, $token);
    } else {
        sendTelegramMessage($chatId, "I'm sorry, I encountered an error processing your request.", $token);
    }

} catch (Exception $e) {
    error_log("Telegram Webhook Error: " . $e->getMessage());
}
