<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Services\PoolService;
use App\Models\PoolDistribution;
use App\Models\PoolShare;
use App\Models\Setting;
use Illuminate\Http\Request;

class PoolController extends Controller
{
    protected $poolService;
    
    public function __construct(PoolService $poolService)
    {
        $this->poolService = $poolService;
    }
    
    public function index()
    {
        try {
            $stats = $this->poolService->getPoolStats();
            
            $previousMonthStats = $this->poolService->getPoolStats(
                now()->subMonth()->month,
                now()->subMonth()->year
            );
            
            // Récupérer l'historique des distributions agrégé par mois/année
            $distributions = PoolDistribution::selectRaw('
                    month, 
                    year, 
                    MAX(total_pool) as total_pool,
                    COUNT(DISTINCT user_id) as total_distributors,
                    SUM(amount) as total_distributed,
                    AVG(amount) as avg_per_person,
                    MAX(created_at) as created_at
                ')
                ->groupBy('month', 'year')
                ->orderBy('year', 'desc')
                ->orderBy('month', 'desc')
                ->take(12)
                ->get();
            
            $recentShares = PoolShare::with('user')
                ->where('status', 'paid')
                ->orderBy('paid_at', 'desc')
                ->take(10)
                ->get();
            
            return view('admin.pool.index', compact('stats', 'previousMonthStats', 'distributions', 'recentShares'));
        } catch (\Exception $e) {
            \Log::error('Erreur PoolController@index: ' . $e->getMessage());
            return back()->with('error', 'Erreur de chargement: ' . $e->getMessage());
        }
    }
    
    public function updateSettings(Request $request)
    {
        $validated = $request->validate([
            'pool_percentage' => 'required|numeric|min:1|max:50',
            'minimum_monthly_purchase' => 'required|numeric|min:0',
            'minimum_referrals_for_pool' => 'required|integer|min:0'
        ]);
        
        try {
            Setting::updateOrCreate(
                ['key' => 'pool_percentage'],
                ['value' => $validated['pool_percentage'], 'type' => 'numeric', 'description' => 'Pourcentage du pool sur les ventes']
            );
            Setting::updateOrCreate(
                ['key' => 'minimum_monthly_purchase'],
                ['value' => $validated['minimum_monthly_purchase'], 'type' => 'numeric', 'description' => 'Achat mensuel minimum pour le pool']
            );
            Setting::updateOrCreate(
                ['key' => 'minimum_referrals_for_pool'],
                ['value' => $validated['minimum_referrals_for_pool'], 'type' => 'integer', 'description' => 'Nombre minimum de filleuls pour le pool']
            );
            
            return back()->with('success', 'Paramètres du pool mis à jour avec succès.');
        } catch (\Exception $e) {
            return back()->with('error', 'Erreur: ' . $e->getMessage());
        }
    }
    
    public function distribute()
    {
        try {
            $result = $this->poolService->distributePool();
            
            if ($result['success']) {
                return redirect()->route('admin.pool.index')
                    ->with('success', $result['message'] . ' Montant: ' . number_format($result['total_amount'], 0, ',', ' ') . ' XOF pour ' . $result['distributors_count'] . ' distributeurs.');
            }
            
            return back()->with('error', $result['message']);
        } catch (\Exception $e) {
            return back()->with('error', 'Erreur: ' . $e->getMessage());
        }
    }
    
    public function history()
    {
        $shares = PoolShare::with('user')
            ->orderBy('created_at', 'desc')
            ->paginate(20);
        
        $totalDistributed = PoolShare::sum('amount');
        $totalDistributors = PoolShare::distinct('user_id')->count('user_id');
        
        return view('admin.pool.history', compact('shares', 'totalDistributed', 'totalDistributors'));
    }
    
    public function showDetails($month, $year)
    {
        $shares = PoolShare::with('user')
            ->whereYear('period_start', $year)
            ->whereMonth('period_start', $month)
            ->orderBy('amount', 'desc')
            ->get();
        
        $totalAmount = $shares->sum('amount');
        
        return view('admin.pool.details', compact('shares', 'totalAmount', 'month', 'year'));
    }
}
