<?php
// api/search_guest.php
require_once __DIR__ . '/../config.php';
startSecureSession();

$isPublic = !empty($_GET['public']);

if (!$isPublic && empty($_SESSION['checker_id']) && empty($_SESSION['admin_id'])) {
    jsonOut(['error' => 'Unauthorized'], 401);
}

$q       = trim($_GET['q'] ?? '');
$eventId = (int)($_GET['event_id'] ?? 0);
if (!$q || !$eventId) { jsonOut([]); }

$db   = db();
$like = '%' . $q . '%';

if ($isPublic) {
    $stmt = $db->prepare(
        'SELECT id, name, email, category, table_number, seat_number, checked_in, invite_path
         FROM guests WHERE event_id=? AND (name LIKE ? OR email LIKE ?)
         ORDER BY name ASC LIMIT 10'
    );
    $stmt->execute([$eventId, $like, $like]);
} else {
    $stmt = $db->prepare(
        'SELECT id, name, email, phone, category, table_number, seat_number,
                checked_in, check_in_time, check_in_method, invite_path
         FROM guests WHERE event_id=? AND (name LIKE ? OR email LIKE ? OR phone LIKE ?)
         ORDER BY checked_in ASC, name ASC LIMIT 20'
    );
    $stmt->execute([$eventId, $like, $like, $like]);
}
jsonOut($stmt->fetchAll());
