<?php
// api/news_mentions.php

declare(strict_types=1);

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/news_common.php';

try {
    rvu_ensure_news_tables($pdo);
    rvu_news_require_user($pdo);
    if (strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'GET') {
        rvu_news_json(['detail' => 'Method not allowed.'], 405);
    }

    $query = trim((string)($_GET['q'] ?? ''));
    if ($query === '') {
        rvu_news_json(['data' => []]);
    }

    $stmt = $pdo->prepare("SELECT id, full_name, role, COALESCE(campus, '') AS campus, COALESCE(profile_picture, '') AS profile_picture
                           FROM users
                           WHERE full_name ILIKE :q OR email ILIKE :q
                           ORDER BY full_name ASC
                           LIMIT 12");
    $stmt->execute([':q' => '%' . $query . '%']);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    foreach ($rows as &$row) $row['id'] = (int)$row['id'];
    unset($row);
    rvu_news_json(['data' => $rows]);
} catch (Throwable $e) {
    rvu_news_json(['detail' => 'Mention search server error: ' . $e->getMessage()], 500);
}
