<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\ReferralEvent;
use Illuminate\Support\Facades\Auth;

class ReferralController extends Controller
{
    public function index()
    {
        $user = Auth::user();
        $code = $user->referralCode();
        $referralUrl = route('referral.redirect', $code);

        $referredUsers = $user->referredUsers()
            ->latest()
            ->take(20)
            ->get();

        $events = ReferralEvent::with('referredUser')
            ->where('referrer_id', $user->id)
            ->latest()
            ->take(20)
            ->get();

        $stats = [
            'users_referred' => $user->referredUsers()->count(),
            'referral_earnings' => ReferralEvent::where('referrer_id', $user->id)
                ->where('type', 'commission')
                ->sum('reward_points'),
            'commission_rate' => (float) site_setting('referral_commission_percent', (float) config('rewards.referral_commission_rate', 0.05) * 100),
            'signup_bonus' => (float) site_setting('referral_signup_bonus', config('rewards.referral_signup_bonus', 5)),
        ];

        return view('user.referrals', compact('code', 'referralUrl', 'referredUsers', 'events', 'stats'));
    }
}
