<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ReferralEvent;
use App\Models\User;
use Illuminate\Http\Request;

class ReferralsController extends Controller
{
    public function index(Request $request)
    {
        $events = ReferralEvent::with(['referrer', 'referredUser'])
            ->when($request->filled('type'), fn ($query) => $query->where('type', $request->input('type')))
            ->latest()
            ->paginate(20)
            ->withQueryString();

        $topReferrers = User::withCount('referredUsers')
            ->where('referral_earnings', '>', 0)
            ->orWhereHas('referredUsers')
            ->orderByDesc('referral_earnings')
            ->take(10)
            ->get();

        $stats = [
            'referrers' => User::whereHas('referredUsers')->count(),
            'referred_users' => User::whereNotNull('referred_by')->count(),
            'referral_earnings' => ReferralEvent::sum('reward_points'),
            'commissions' => ReferralEvent::where('type', 'commission')->count(),
        ];

        return view('admin.referrals', compact('events', 'topReferrers', 'stats'));
    }
}
