<?php
// Set header JSON dan cegah output lain
header('Content-Type: application/json; charset=utf-8');
ob_clean();
error_reporting(0);

require_once __DIR__ . '/../includes/config.php'; // sesuaikan dengan struktur proyek

try {
    $q = trim($_GET['q'] ?? '');
    
    // Jika input kosong, langsung kirim array kosong
    if ($q === '' || strlen($q) < 2) {
        echo json_encode([]);
        exit;
    }

    // Query aman pakai prepared statement
    $stmt = $pdo->prepare("SELECT title FROM documents WHERE title LIKE :q ORDER BY created_at DESC LIMIT 10");
    $stmt->execute([':q' => "%$q%"]);

    $results = $stmt->fetchAll(PDO::FETCH_COLUMN);

    // Pastikan output berupa array kosong jika tidak ada hasil
    echo json_encode($results ?: [], JSON_UNESCAPED_UNICODE);

} catch (Throwable $e) {
    // Tangani error dengan aman, jangan bocorkan detail server
    http_response_code(500);
    echo json_encode(['error' => 'Server error, tidak dapat memproses permintaan.']);
    // Jika debugging: uncomment baris berikut
    // echo json_encode(['error' => $e->getMessage()]);
}
