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

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

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

try {
    // 1. Authenticate
    $user_id = Auth::check(); // Returns user ID from token

    // 2. Fetch User Data
    $stmt = $pdo->prepare("SELECT iuid, i_username, i_user_email, user_avatar, user_cover, level, xp, diamonds, uStatus FROM i_users WHERE iuid = ?");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        http_response_code(404);
        echo json_encode(['error' => 'User not found']);
        exit;
    }

    // Normalizar avatar a URL absoluta
    $server_url = "http://localhost/Juuvix_Shop/KLKAPP%20TEST";
    $avatar = $user['user_avatar'];
    if ($avatar && $avatar !== 'default.png') {
        if (preg_match('/avatars[\\\\\/]([^\\\\\/]+)$/', $avatar, $matches)) {
            $avatar = $server_url . "/avatars/" . $matches[1];
        } else if (strpos($avatar, 'http') === false) {
            $avatar = $server_url . "/avatars/" . basename($avatar);
        }
    }

    $cover = $user['user_cover'];
    if ($cover && $cover !== 'default.png' && strpos($cover, 'http') === false) {
        $cover = $server_url . "/covers/" . basename($cover);
    }

    // 3. Map to Frontend Structure
    $frontendUser = [
        'id' => $user['iuid'],
        'username' => $user['i_username'],
        'email' => $user['i_user_email'],
        'avatar' => $avatar,
        'cover' => $cover,
        'level' => $user['level'],
        'xp' => $user['xp'],
        'diamonds' => $user['diamonds']
    ];

    echo json_encode([
        'success' => true,
        'user' => $frontendUser
    ]);

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