<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Leaderboard;
use App\Services\LeaderboardService;
use Illuminate\Http\Request;

class LeaderboardController extends Controller
{
    protected $leaderboardService;

    public function __construct(LeaderboardService $leaderboardService)
    {
        $this->leaderboardService = $leaderboardService;
    }

    public function index(Request $request)
    {
        $type = $request->get('type', 'top_seller');
        $period = $request->get('period', 'monthly');

        $leaderboards = Leaderboard::with('user')
            ->where('type', $type)
            ->where('period', $period)
            ->current()
            ->orderBy('rank')
            ->paginate(50);

        $types = [
            'top_seller' => 'Top Vendeurs',
            'top_buyer' => 'Top Acheteurs',
            'top_sponsor' => 'Top Parrains',
            'top_leader' => 'Top Leaders MLM'
        ];

        $periods = [
            'weekly' => 'Hebdomadaire',
            'monthly' => 'Mensuel',
            'quarterly' => 'Trimestriel',
            'yearly' => 'Annuel',
        ];

        // Statistiques
        $stats = [
            'total_entries' => Leaderboard::where('period', $period)->current()->count(),
            'types_count' => Leaderboard::where('period', $period)->current()->distinct('type')->count('type'),
        ];

        return view('admin.leaderboards.index', compact('leaderboards', 'types', 'periods', 'type', 'period', 'stats'));
    }

    public function calculate(Request $request)
    {
        $type = $request->get('type', 'all');
        $period = $request->get('period', 'monthly');

        if ($type === 'all') {
            $this->leaderboardService->calculateAllLeaderboards($period);
            $message = 'Tous les classements ont été recalculés';
        } else {
            $this->leaderboardService->calculateLeaderboard($type, $period);
            $message = 'Classement recalculé';
        }

        return redirect()->back()->with('success', $message);
    }

    public function reset(Request $request)
    {
        $type = $request->get('type');
        $period = $request->get('period');

        $query = Leaderboard::query();
        
        if ($type) {
            $query->where('type', $type);
        }
        if ($period) {
            $query->where('period', $period);
        }

        $query->delete();

        return redirect()->back()->with('success', 'Classements réinitialisés');
    }
}
