<?php
require_once __DIR__ . '/../config/secure_bootstrap.php';

// Set header JSON
header('Content-Type: application/json; charset=utf-8');

// Ambil query dari parameter GET
$q = trim($_GET['term'] ?? ''); // jQuery UI kirim parameter "term"
if ($q === '') {
    echo json_encode([]);
    exit;
}

// Query pencarian (cari di seluruh kolom utama)
$like = "%$q%";
$stmt = $pdo->prepare("
    SELECT 
        id, 
        title, 
        description, 
        organizer, 
        location, 
        CONCAT(title, ' - ', COALESCE(location, ''), ' (', COALESCE(organizer, ''), ')') AS label
    FROM activities
    WHERE 
        title LIKE ? 
        OR description LIKE ? 
        OR organizer LIKE ? 
        OR location LIKE ?
    ORDER BY date_start DESC
    LIMIT 15
");
$stmt->execute([$like, $like, $like, $like]);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Format output untuk jQuery UI autocomplete
$output = [];
foreach ($results as $row) {
    $output[] = [
        'id' => $row['id'],
        'label' => $row['label'],
        'value' => $row['title'],  // Nilai yang akan diisi ke input
        'location' => $row['location'],
        'organizer' => $row['organizer'],
        'description' => $row['description']
    ];
}

echo json_encode($output, JSON_UNESCAPED_UNICODE);
exit;
