<?php
header('Content-Type: application/json');

require_once __DIR__ . '/../classes/Database.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../classes/Messaging.php';

try {
    session_start();
    if (empty($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'message' => 'Login required.']);
        exit;
    }

    $query = trim((string)($_GET['q'] ?? ''));

    $database = new Database();
    $conn = $database->getConnection();

    $messaging = new Messaging($conn);
    $users = $messaging->searchUsers($query, (int)$_SESSION['user_id']);
    echo json_encode(['success' => true, 'users' => $users]);
} catch (Throwable $e) {
    error_log('User search for messaging failed: ' . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Unable to search users.']);
}
