<?php

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

require_once __DIR__ . '/../includes/supabase.php';
require_once __DIR__ . '/../includes/auth.php';

$token = requireAuth();
$userId = getUserId($token);
$db = supabase($token);

$achievements = $db->get('achievements', ['select' => 'id,name,name_ar,description,description_ar,category,xp_reward,coins_reward,icon']);
$playerAchievements = $db->get('player_achievements', ['player_id' => 'eq.' . $userId, 'select' => 'achievement_id,progress,is_completed,completed_at']);

$playerMap = [];
if (is_array($playerAchievements) && !isset($playerAchievements['error'])) {
    foreach ($playerAchievements as $pa) {
        $playerMap[$pa['achievement_id']] = $pa;
    }
}

$result = [];
if (is_array($achievements) && !isset($achievements['error'])) {
    foreach ($achievements as $a) {
        $a['player_progress'] = $playerMap[$a['id']]['progress'] ?? 0;
        $a['is_completed'] = $playerMap[$a['id']]['is_completed'] ?? false;
        $result[] = $a;
    }
}

jsonResponse(['achievements' => $result]);
