<?php
// bot_reply.php
// simple search-based auto reply that scans text in site files and also checks keywords
function get_auto_reply($userMessage, $pdo, $site_root) {
  $msg = mb_strtolower($userMessage, 'UTF-8');

  // 1) quick keyword canned replies
  $keywords = [
    'prix' => "Salam! L'prix huwa X DH. Bghiti n-sift lik info mazal?",
    'tarif' => "Prix/test: contact@domain.com, aw tla3 l-page tarifs.",
    'bonjour' => "Wa 3alaykom salam! Kif n3awnk?",
    'salam' => "Wa 3alaykom salam! Kif n3awnk?",
    'contact' => "Rak t9dar t3ayet l: 06XXXXXXXX ou t-sift mail: contact@exemple.com",
    'horaire' => "L'horaire: mn 9:00 ta 18:00 (lun-ven)."
  ];
  foreach($keywords as $k => $reply){
    if(mb_strpos($msg, $k) !== false) return $reply;
  }

  // 2) search inside site files (basic full-text)
  $foundSnippets = [];
  $maxFiles = 200; $checked = 0;
  $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($site_root));
  foreach($it as $file){
    if($checked >= $maxFiles) break;
    if(!$file->isFile()) continue;
    $ext = strtolower(pathinfo($file->getFilename(), PATHINFO_EXTENSION));
    if(!in_array($ext, ['html','htm','php','txt'])) continue;
    $content = @file_get_contents($file->getPathname());
    if(!$content) continue;
    $lc = mb_strtolower(strip_tags($content), 'UTF-8');
    if(mb_strpos($lc, $msg) !== false){
      // grab short snippet
      $pos = mb_strpos($lc, $msg);
      $start = max(0, $pos - 80);
      $snippet = mb_substr($lc, $start, 300);
      $foundSnippets[] = [
        'file' => str_replace($site_root, '', $file->getPathname()),
        'snippet' => trim(preg_replace('/\s+/u',' ', $snippet))
      ];
      if(count($foundSnippets) >= 3) break;
    }
    $checked++;
  }

  if(count($foundSnippets)){
    // build reply summarizing matches
    $reply = "Hadi chi 7wayej li l9it f-site:\n";
    foreach($foundSnippets as $s){
      $reply .= "- " . trim($s['file']) . ": «" . mb_substr($s['snippet'],0,200) . "...»\n";
    }
    $reply .= "Bghiti n-ftah lik l-page mbashar?";
    return $reply;
  }

  // 3) optional fallback: search DB pages if you have a pages table (example)
  // (if you keep site content in DB, add code here to full-text search)

  // 4) default fallback
  return "Smah li — ma l9it 7aja m-match. T9dar t-3awd t-sawal b-kalam akthar w t-jawd l-bot.";
}
