<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Auth;

class BadgeResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        $isUnlocked = false;
        $user = Auth::user();
        if ($user && $user->relationLoaded('userBadges')) {
             $isUnlocked = $user->userBadges->contains('badge_id', $this->id);
        } elseif ($user) {
             // Fallback if not eager loaded (less efficient but works)
             $isUnlocked = $user->userBadges()->where('badge_id', $this->id)->exists();
        }

        return [
            'id' => $this->id,
            'name_fa' => $this->name_fa,
            'name_en' => $this->name_en,
            'description' => $this->description,
            'icon' => $this->icon,
            'color' => $this->color,
            'points_required' => $this->points_required,
            'is_unlocked' => $isUnlocked,
        ];
    }
}
