<?php

namespace App\Http\Controllers\Frontend;

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

class TeamController extends Controller
{
  
    public function index()
    {
        $user = Auth::user();
         $commission = Commission::first();
        
        // Get team statistics
        $totalReferrals = $user->referrals()->count();
        $totalTeamMembers = $this->getAllTeamMembersCount($user);
        
        // Get level-wise counts
        $level1Count = $user->referrals()->count();
        $level2Count = $this->getLevelCount($user, 2);
        $level3Count = $this->getLevelCount($user, 3);
        
        // Get active/inactive counts
        $activeMembers = $user->referrals()->where('status', 1)->count();
        $inactiveMembers = $user->referrals()->where('status', 0)->count();
        $vipMembers = $user->referrals()->whereHas('vipInvestments')->count();
        
        // Get team earnings
        $teamEarnings = $this->getTeamEarnings($user);
        $todayEarnings = $this->getTodayEarnings($user);
        
        // Get team deposits
        $teamDeposits = $this->getTeamDeposits($user);
        $level1Deposits = $this->getLevelDeposits($user, 1);
        $level2Deposits = $this->getLevelDeposits($user, 2);
        $level3Deposits = $this->getLevelDeposits($user, 3);
        
        // Get VIP products for display - using where() instead of scope for safety
        $vipProducts = VipProduct::where('is_active', true)->orderBy('price')->get();

        return view('user.team.index', compact(
            'user',
            'totalReferrals',
            'totalTeamMembers',
            'level1Count',
            'level2Count',
            'level3Count',
            'activeMembers',
            'inactiveMembers',
            'vipMembers',
            'teamEarnings',
            'todayEarnings',
            'teamDeposits',
            'level1Deposits',
            'level2Deposits',
            'level3Deposits',
            'vipProducts',
              'commission'
        ));
    }



    private function getAllTeamMembersCount($user, $level = 1, $maxLevel = 3)
    {
        if ($level > $maxLevel) return 0;
        
        $count = $user->referrals()->count();
        
        foreach ($user->referrals as $referral) {
            $count += $this->getAllTeamMembersCount($referral, $level + 1, $maxLevel);
        }
        
        return $count;
    }

    private function getLevelCount($user, $targetLevel, $currentLevel = 1)
    {
        if ($currentLevel > $targetLevel) return 0;
        
        $count = 0;
        
        if ($currentLevel === $targetLevel) {
            return $user->referrals()->count();
        }
        
        foreach ($user->referrals as $referral) {
            $count += $this->getLevelCount($referral, $targetLevel, $currentLevel + 1);
        }
        
        return $count;
    }

    private function getTeamEarnings($user)
    {
        // Sum of all referral earnings from transactions
        return Transaction::whereIn('user_id', $this->getAllTeamMemberIds($user))
            ->where('type', 'referral_bonus')
            ->sum('amount');
    }

    private function getTodayEarnings($user)
    {
        // Today's referral earnings
        return Transaction::whereIn('user_id', $this->getAllTeamMemberIds($user))
            ->where('type', 'referral_bonus')
            ->whereDate('created_at', today())
            ->sum('amount');
    }

    private function getTeamDeposits($user)
    {
        // Sum of all deposits by team members
        return Transaction::whereIn('user_id', $this->getAllTeamMemberIds($user))
            ->where('type', 'deposit')
            ->where('status', 'approved')
            ->sum('amount');
    }

    private function getLevelDeposits($user, $targetLevel, $currentLevel = 1)
    {
        if ($currentLevel > $targetLevel) return 0;
        
        $amount = 0;
        
        if ($currentLevel === $targetLevel) {
            $userIds = $user->referrals()->pluck('id');
            return Transaction::whereIn('user_id', $userIds)
                ->where('type', 'deposit')
                ->where('status', 'approved')
                ->sum('amount');
        }
        
        foreach ($user->referrals as $referral) {
            $amount += $this->getLevelDeposits($referral, $targetLevel, $currentLevel + 1);
        }
        
        return $amount;
    }

    private function getAllTeamMemberIds($user, $level = 1, $maxLevel = 3)
    {
        if ($level > $maxLevel) return [];
        
        $ids = $user->referrals()->pluck('id')->toArray();
        
        foreach ($user->referrals as $referral) {
            $ids = array_merge($ids, $this->getAllTeamMemberIds($referral, $level + 1, $maxLevel));
        }
        
        return $ids;
    }
}