<?php
require_once '../../config/db.php';
require_once '../../core/Auth.php';

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

try {
    // Depuración: Desactivar Auth temporalmente para probar visibilidad
    // $my_id = Auth::check();
    
    $query = isset($_GET['q']) ? trim($_GET['q']) : '';
    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 20;

    if (empty($query)) {
        // Si no hay query, devolver usuarios recientes o sugeridos
        $sql = "SELECT iuid as id, i_username as username, i_user_email as email, level, user_avatar as avatar 
                FROM i_users 
                ORDER BY registered DESC 
                LIMIT $limit";
        $stmt = $pdo->prepare($sql);
        $stmt->execute();
    } else {
        // Buscar por nombre o email
        $sql = "SELECT iuid as id, i_username as username, i_user_email as email, level, user_avatar as avatar 
                FROM i_users 
                WHERE (i_username LIKE ? OR i_user_email LIKE ?) 
                ORDER BY i_username ASC 
                LIMIT $limit";
        $stmt = $pdo->prepare($sql);
        $searchParam = "%$query%";
        $stmt->execute([$searchParam, $searchParam]);
    }

    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Normalizar avatares: si es una ruta de sistema, convertir a URL web absoluta
    $server_url = "http://localhost/Juuvix_Shop/KLKAPP%20TEST";
    foreach ($users as &$u) {
        if ($u['avatar'] && $u['avatar'] !== 'default.png') {
            // Limpiar cualquier ruta de sistema y dejar solo el nombre del archivo
            if (preg_match('/avatars[\\\\\/]([^\\\\\/]+)$/', $u['avatar'], $matches)) {
                $u['avatar'] = $server_url . "/avatars/" . $matches[1];
            } else if (strpos($u['avatar'], 'http') === false) {
                // Si no es URL y no coincide con el pattern anterior, intentar limpiar por nombre
                $u['avatar'] = $server_url . "/avatars/" . basename($u['avatar']);
            }
        }
    }

    echo json_encode([
        'query' => $query,
        'count' => count($users),
        'data' => $users
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}
?>
