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

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

try {
    // Optional Auth check if we want public profiles to be visible? 
    // For now let's require auth to see lists or at least identified user
    // $my_id = Auth::check(); 
    
    $user_id = isset($_GET['user_id']) ? (int)$_GET['user_id'] : 0;
    $type = isset($_GET['type']) ? $_GET['type'] : 'followers'; // 'followers' or 'following'

    if ($user_id === 0) {
        http_response_code(400);
        echo json_encode(['error' => 'User ID required']);
        exit;
    }

    if ($type === 'followers') {
        // Who follows this user?
        $sql = "SELECT u.iuid as id, u.i_username as username, u.i_user_email as email, u.level, u.user_avatar as avatar 
                FROM follows f 
                JOIN i_users u ON f.follower_id = u.iuid 
                WHERE f.following_id = ?";
    } else {
         // Who is this user following?
        $sql = "SELECT u.iuid as id, u.i_username as username, u.i_user_email as email, u.level, u.user_avatar as avatar 
                FROM follows f 
                JOIN i_users u ON f.following_id = u.iuid 
                WHERE f.follower_id = ?";
    }

    $stmt = $pdo->prepare($sql);
    $stmt->execute([$user_id]);
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Normalizar avatares
    // Normalizar avatares a URLs absolutas
    $server_url = "http://localhost/Juuvix_Shop/KLKAPP%20TEST";
    foreach ($users as &$u) {
        if ($u['avatar'] && $u['avatar'] !== 'default.png') {
            if (preg_match('/avatars[\\\\\/]([^\\\\\/]+)$/', $u['avatar'], $matches)) {
                $u['avatar'] = $server_url . "/avatars/" . $matches[1];
            } else if (strpos($u['avatar'], 'http') === false) {
                $u['avatar'] = $server_url . "/avatars/" . basename($u['avatar']);
            }
        }
    }

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

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