<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Services\TopSponsorService;
use Illuminate\Http\Request;
use Carbon\Carbon;

class TopSponsorController extends Controller
{
    protected TopSponsorService $topSponsorService;

    public function __construct(TopSponsorService $topSponsorService)
    {
        $this->topSponsorService = $topSponsorService;
    }

    /**
     * Afficher le classement des parrains
     */
    public function index(Request $request)
    {
        $month = $request->input('month', now()->month);
        $year = $request->input('year', now()->year);

        // Créer un objet Carbon à partir du mois et de l'année
        $carbonDate = Carbon::createFromDate($year, $month, 1);

        $leaderboard = $this->topSponsorService->getMonthlyLeaderboard($carbonDate, 20);
        $sponsorOfMonth = $this->topSponsorService->getSponsorOfTheMonth($carbonDate);

        // Statistiques générales
        $stats = [
            'total_referrals_this_month' => \App\Models\User::whereMonth('created_at', $month)
                ->whereYear('created_at', $year)
                ->whereNotNull('referrer_id')
                ->count(),
            'active_sponsors' => \App\Models\User::whereHas('referrals', function($q) use ($month, $year) {
                $q->whereMonth('created_at', $month)->whereYear('created_at', $year);
            })->count(),
            'total_commissions' => \App\Models\Commission::whereMonth('created_at', $month)
                ->whereYear('created_at', $year)
                ->sum('amount'),
        ];

        return view('admin.top-sponsors.index', compact('leaderboard', 'sponsorOfMonth', 'stats', 'month', 'year'));
    }

    /**
     * Attribuer le bonus au parrain du mois
     */
    public function awardTopSponsor(Request $request)
    {
        $request->validate([
            'user_id' => 'required|exists:users,id',
            'bonus_amount' => 'required|numeric|min:0',
            'month' => 'required|integer|min:1|max:12',
            'year' => 'required|integer|min:2020',
        ]);

        $user = \App\Models\User::findOrFail($request->user_id);
        
        $result = $this->topSponsorService->awardTopSponsor(
            $user,
            $request->bonus_amount,
            $request->month,
            $request->year
        );

        if ($result) {
            return back()->with('success', "Bonus de {$request->bonus_amount} FCFA attribué à {$user->name} pour être le parrain du mois!");
        }

        return back()->with('error', 'Erreur lors de l\'attribution du bonus.');
    }

    /**
     * Historique des parrains du mois
     */
    public function history()
    {
        // Récupérer les transactions de type top_sponsor_bonus
        $history = \App\Models\WalletTransaction::where('type', 'top_sponsor_bonus')
            ->with('user')
            ->orderBy('created_at', 'desc')
            ->paginate(20);

        return view('admin.top-sponsors.history', compact('history'));
    }
}
