"I didn't catch that. Could you repeat?"]); exit; } $faqs = db()->query("SELECT keywords, answer FROM faqs")->fetchAll(); $bestMatch = null; $maxOverlap = 0; $userWords = preg_split('/\W+/', strtolower($message), -1, PREG_SPLIT_NO_EMPTY); foreach ($faqs as $faq) { $keywords = preg_split('/[\s,]+/', strtolower($faq['keywords']), -1, PREG_SPLIT_NO_EMPTY); $overlap = count(array_intersect($userWords, $keywords)); if ($overlap > $maxOverlap) { $maxOverlap = $overlap; $bestMatch = $faq['answer']; } } if ($bestMatch) { echo json_encode(['reply' => $bestMatch]); } else { // Default fallback echo json_encode(['reply' => "I'm sorry, I don't have an answer for that yet. You can try asking about 'pricing' or 'support'."]); }