<?php
require_once __DIR__ . '/../config/database.php';

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

$token = get_auth_token();

if (!$token) {
    http_response_code(401);
    echo json_encode(['error' => 'unauthorized']);
    exit;
}

$category = $_GET['category'] ?? null;

$endpoint = 'achievements?select=*&order=category.asc,tier.asc';
if ($category) {
    $endpoint .= '&category=eq.' . $category;
}

$achRes = supabase_rest('GET', $endpoint, [], $token);
$achievements = ($achRes['status'] === 200 && is_array($achRes['data']) && !isset($achRes['data']['code'])) ? $achRes['data'] : [];

if (!empty($achievements)) {
    $unlockedRes = supabase_rest('GET', 'player_achievements?select=achievement_id,unlocked_at', [], $token);
    $unlocked = [];
    if ($unlockedRes['status'] === 200 && is_array($unlockedRes['data'])) {
        foreach ($unlockedRes['data'] as $row) {
            $unlocked[$row['achievement_id']] = $row['unlocked_at'];
        }
    }

    foreach ($achievements as &$ach) {
        $ach['unlocked'] = isset($unlocked[$ach['id']]);
        $ach['unlocked_at'] = $unlocked[$ach['id']] ?? null;
        $ach['progress'] = 0;
    }
}

echo json_encode(['achievements' => $achievements]);
