<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;

class ReferralController extends Controller
{
    /**
     * ===============================
     * DOWNLINE
     * ===============================
     */
    public function downline(Request $request)
    {
        $query = Auth::user()->referrals();

        // 🔥 FILTER TANGGAL (OPTIONAL)
        if ($request->daterange) {
            $dates = explode(' - ', $request->daterange);

            if (count($dates) == 2) {
                $start = $dates[0];
                $end   = $dates[1];

                $query->whereBetween('created_at', [$start, $end]);
            }
        }

        $downlines = $query->latest()->get();

        return view('refferal', compact('downlines'));
    }

    /**
     * ===============================
     * BONUS
     * ===============================
     */
    public function bonus()
    {
        $downlines = Auth::user()->referrals;

        $totalTurnover = $downlines->sum('user_turnover');

        // contoh 0.2%
        $bonus = $totalTurnover * 0.002;

        return view('referral_bonus', compact('downlines','totalTurnover','bonus'));
    }
}