36 lines
1.0 KiB
PHP
36 lines
1.0 KiB
PHP
<?php
|
|
header('Content-Type: application/json');
|
|
require_once __DIR__ . '/../db/config.php';
|
|
|
|
$input = json_decode(file_get_contents('php://input'), true);
|
|
$message = $input['message'] ?? '';
|
|
|
|
if (empty($message)) {
|
|
echo json_encode(['reply' => "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'."]);
|
|
}
|