<?php

namespace App\Http\Controllers\Member;

use App\Http\Controllers\Controller;
use App\Models\Badge;
use App\Models\Order;
use App\Models\Commission;
use Illuminate\Support\Facades\DB;

class BadgeController extends Controller
{
    public function index()
    {
        $user = auth()->user();
        
        // Mes badges obtenus avec les détails
        $userBadges = DB::table('user_badges')
            ->join('badges', 'user_badges.badge_id', '=', 'badges.id')
            ->where('user_badges.user_id', $user->id)
            ->select('badges.*', 'user_badges.period', 'user_badges.period_date', 'user_badges.awarded_at')
            ->orderByDesc('user_badges.awarded_at')
            ->get();
        
        $userBadgeIds = $userBadges->pluck('id')->toArray();
        
        // Tous les badges disponibles (actifs)
        $allBadges = Badge::where('is_active', true)->get();
        
        // Badges pas encore obtenus
        $availableBadges = $allBadges->whereNotIn('id', $userBadgeIds);
        
        // Statistiques pour voir la progression
        $stats = [
            'total_badges' => $allBadges->count(),
            'earned_badges' => count($userBadgeIds),
            'total_points' => $userBadges->sum('points_value'),
            'orders_count' => Order::where('user_id', $user->id)->where('status', 'completed')->count(),
            'referrals_count' => $user->referrals()->count(),
            'commissions_total' => Commission::where('user_id', $user->id)->sum('amount'),
        ];
        
        // Catégories de badges
        $categories = $allBadges->groupBy('category');
        
        return view('member.badges.index', compact(
            'userBadges', 
            'allBadges', 
            'availableBadges',
            'userBadgeIds', 
            'stats',
            'categories'
        ));
    }
}
