<?php
header('Content-Type: application/json');
require_once 'auth/session.php';
requireLogin();

$user_id = $_SESSION['user_id'];
$query = $_GET['q'] ?? '';
$type = $_GET['type'] ?? 'messages'; // messages or users
$channel_id = $_GET['channel_id'] ?? 0;

if (empty($query)) {
    echo json_encode(['success' => true, 'results' => []]);
    exit;
}

try {
    if ($type === 'users') {
        $stmt = db()->prepare("
            SELECT id, username, avatar_url, status 
            FROM users 
            WHERE username LIKE ? 
            LIMIT 20
        ");
        $stmt->execute(["%" . $query . "%"]);
        $results = $stmt->fetchAll();
    } else {
        $sql = "SELECT m.*, u.username, u.avatar_url 
                FROM messages m 
                JOIN users u ON m.user_id = u.id 
                WHERE m.content LIKE ? ";
        $params = ["%" . $query . "%"];

        if ($channel_id > 0) {
            $sql .= " AND m.channel_id = ?";
            $params[] = $channel_id;
        } else {
            // Search in all channels user has access to
            $sql .= " AND m.channel_id IN (
                SELECT c.id FROM channels c 
                LEFT JOIN server_members sm ON c.server_id = sm.server_id 
                LEFT JOIN channel_members cm ON c.id = cm.channel_id
                WHERE sm.user_id = ? OR cm.user_id = ?
            )";
            $params[] = $user_id;
            $params[] = $user_id;
        }

        $sql .= " ORDER BY m.created_at DESC LIMIT 50";
        $stmt = db()->prepare($sql);
        $stmt->execute($params);
        $results = $stmt->fetchAll();
    }

    echo json_encode(['success' => true, 'results' => $results]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
