<?php
declare(strict_types=1);

namespace App\Modules\PlayerApi\Controllers\Api;

use App\Core\ApiController;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;

final class AchievementController extends ApiController
{
    public function index(Request $request): Response
    {
        $player = App::getInstance()->currentPlayer();
        $db = App::getInstance()->db();

        $achievements = $db->select(
            "SELECT pa.earned_at, pa.points_earned,
                    ad.name_ar, ad.name_en, ad.description_ar, ad.icon, ad.badge_color, ad.category
             FROM player_achievements pa
             JOIN achievement_definitions ad ON ad.id = pa.achievement_id
             WHERE pa.player_id = ?
             ORDER BY pa.earned_at DESC",
            [(int) $player->id]
        );

        $totalPoints = array_sum(array_column($achievements, 'points_earned'));

        return $this->successResponse([
            'total_points' => $totalPoints,
            'achievements' => $achievements,
        ]);
    }
}
