<?php
require 'Login/config.php';
header('Content-Type: application/json; charset=utf-8');

$search = trim($_GET['search'] ?? '');
if ($search === '') {
  echo json_encode([]);
  exit;
}

// helper: bikin snippet sinopsis yang aman & pendek
function make_snippet(?string $text, string $q, int $max = 90): string {
  if (!$text) return '';
  $text = strip_tags($text);
  $text = preg_replace('/\s+/u', ' ', $text); // rapikan spasi
  $pos  = mb_stripos($text, $q);
  if ($pos === false) {
    return mb_substr($text, 0, $max) . (mb_strlen($text) > $max ? '…' : '');
  }
  $start = max(0, $pos - intval($max/3));
  $chunk = mb_substr($text, $start, $max);
  return ($start > 0 ? '…' : '') . $chunk . (mb_strlen($text) > $start + $max ? '…' : '');
}

// Jika kueri ≥ 3 huruf, coba FULLTEXT BOOLEAN MODE dengan prefix (*) 
$useFulltext = mb_strlen(preg_replace('/\PL/u', '', $search)) >= 3;

if ($useFulltext) {
  try {
    // ubah "kata1 kata2" -> "+kata1* +kata2*"
    $terms = preg_split('/\s+/u', $search, -1, PREG_SPLIT_NO_EMPTY);
    $boolean = implode(' ', array_map(function($t){
      // buang karakter yang tidak huruf/angka agar tidak error di boolean mode
      $t = preg_replace('/[^\pL\pN]+/u', '', $t);
      if ($t === '') return '';
      return '+' . $t . '*';
    }, $terms));
    $boolean = trim($boolean);
    if ($boolean === '') throw new Exception('empty boolean');

    // MATCH ... AGAINST untuk ranking
    $sql = "
      SELECT 
        id, judul, penulis, isbn, sinopsis,
        MATCH(judul, penulis, isbn, sinopsis) AGAINST(:q IN BOOLEAN MODE) AS score
      FROM books
      WHERE MATCH(judul, penulis, isbn, sinopsis) AGAINST(:q IN BOOLEAN MODE)
      ORDER BY score DESC, created_at DESC
      LIMIT 10
    ";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([':q' => $boolean]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Map hasil + buat snippet
    $out = array_map(function($r) use ($search){
      return [
        'id'               => (int)$r['id'],
        'judul'            => $r['judul'],
        'penulis'          => $r['penulis'],
        'isbn'             => $r['isbn'],
        'sinopsis_snippet' => make_snippet($r['sinopsis'], $search, 90),
      ];
    }, $rows);

    echo json_encode($out);
    exit;
  } catch (Throwable $e) {
    // jatuh ke LIKE fallback di bawah
  }
}

// Fallback LIKE (untuk kueri pendek / FT tidak ada)
$like = '%' . $search . '%';
$sql = "
  SELECT id, judul, penulis, isbn, sinopsis
  FROM books
  WHERE judul   LIKE :q
     OR penulis LIKE :q
     OR isbn    LIKE :q
     OR sinopsis LIKE :q
  ORDER BY created_at DESC
  LIMIT 10
";
$stmt = $pdo->prepare($sql);
$stmt->execute([':q' => $like]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

$out = array_map(function($r) use ($search){
  return [
    'id'               => (int)$r['id'],
    'judul'            => $r['judul'],
    'penulis'          => $r['penulis'],
    'isbn'             => $r['isbn'],
    'sinopsis_snippet' => make_snippet($r['sinopsis'], $search, 90),
  ];
}, $rows);

echo json_encode($out);
