<?php
/**
 * AJAX Handler for AI Chatbot
 * Supports: Gemini AI messages + instant trained suggestion answers
 */
header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['response' => 'Method not allowed.', 'html' => false]);
    exit;
}

require_once 'function.php';

// Trained suggestion — instant answer without Gemini
$training_id = isset($_POST['training_id']) ? intval($_POST['training_id']) : 0;
if ($training_id > 0) {
    global $conn;
    if ($conn) {
        $prefix = DB_PREFIX;
        $stmt = $conn->prepare("SELECT question, answer FROM `{$prefix}chatbot_training` WHERE id = ? AND is_active = 1 LIMIT 1");
        $stmt->bind_param("i", $training_id);
        $stmt->execute();
        $row = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        if ($row) {
            $answer = $row['answer'];
            save_chat_history($row['question'], $answer);
            echo json_encode(['response' => $answer, 'html' => false]);
            exit;
        }
    }
}

$user_message = isset($_POST['message']) ? trim($_POST['message']) : '';
if (empty($user_message)) {
    echo json_encode(['response' => 'অনুগ্রহ করে একটি প্রশ্ন লিখুন।', 'html' => false]);
    exit;
}

try {
    $bot_response = ask_gemini_bot($user_message);
    $has_html = (strpos($bot_response, '<a ') !== false || strpos($bot_response, 'chat-product-card') !== false);
    echo json_encode(['response' => $bot_response, 'html' => $has_html]);
} catch (Exception $e) {
    echo json_encode(['response' => 'প্রযুক্তিগত সমস্যা হচ্ছে। আবার চেষ্টা করুন।', 'html' => false]);
}
exit;
