<?php

namespace App\Http\Controllers\Member;

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

class NetworkController extends Controller
{
    public function index()
    {
        $user = Auth::user();
        
        // Niveau 1 - Tous les filleuls directs
        $level1 = User::where('sponsor_id', $user->id)->get();
        
        // Calculer les commissions reçues de chaque filleul (pour le parrain connecté)
        foreach ($level1 as $member) {
            // Commissions que le parrain (user actuel) a reçues grâce à ce filleul
            $member->commissions_received = Commission::where('user_id', $user->id)
                ->where('from_user_id', $member->id)
                ->sum('amount');
        }
        
        // Niveau 2 - Filleuls des filleuls
        $level2Members = collect();
        $level1Ids = $level1->pluck('id');
        
        if ($level1Ids->isNotEmpty()) {
            $level2All = User::whereIn('sponsor_id', $level1Ids)->get();
            
            // Calculer les commissions reçues de niveau 2 (pour le parrain connecté)
            foreach ($level2All as $member) {
                $member->commissions_received = Commission::where('user_id', $user->id)
                    ->where('from_user_id', $member->id)
                    ->sum('amount');
            }
            
            $level2Members = $level2All->groupBy('sponsor_id');
        }
        
        // Statistiques du réseau
        $stats = [
            'level1_count' => $level1->count(),
            'level1_active' => $level1->where('subscription_paid', true)->count(),
            'level2_count' => $level2Members->flatten()->count(),
            'level2_active' => $level2Members->flatten()->where('subscription_paid', true)->count(),
            'total_network' => $level1->count() + $level2Members->flatten()->count(),
            'total_commissions' => $user->commissions()->sum('amount') ?? 0,
        ];
        
        return view('member.network.index', compact(
            'level1', 
            'level2Members', 
            'stats'
        ));
    }
}