<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Transaction;
use App\Models\Deposit;
use App\Models\Withdrawal;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class MarketerController extends Controller
{
    /**
     * Create a new controller instance.
     */
    public function __construct()
    {
        $this->middleware(['auth', 'verified', 'banned', 'activated']);
    }

    public function marketer(Request $request)
    {
        if (auth()->user()->type != 'marketer') {
            return redirect()->route('home')->with('error', 'Sorry, you do not have access to the Marketers Dashboard.');
        }

        // Cache team IDs for 30 minutes, supports 5 generations
        $cacheKey = 'marketer_team_5gen_' . auth()->id();
        $teamData = Cache::remember($cacheKey, 1800, function () {
            return $this->buildTeamArrays();
        });

        $team = $teamData['team'];
        $first = $teamData['first'];
        $second = $teamData['second'];
        $third = $teamData['third'];
        $fourth = $teamData['fourth'];
        $fifth = $teamData['fifth'];

        // Handle search/filter with pagination
        $membersQuery = User::whereIn('id', $team)
            ->select('id', 'username', 'first_name', 'last_name', 'email', 'balance', 'rebates', 'referrer_id', 'email_verified_at', 'kyc_status');
        
        if ($request->has('filter') && $request->has('value') && $request->value) {
            if ($request->filter == 'email') {
                $membersQuery->where('email', 'like', '%' . $request->value . '%');
            } elseif ($request->filter == 'username') {
                $membersQuery->where('username', 'like', '%' . $request->value . '%');
            }
        }

        // Paginate members
        $members = $membersQuery
            ->withCount('referrals')
            ->orderBy('created_at', 'desc')
            ->paginate(25);

        // Batch calculate stats for current page members
        $memberStats = $this->batchCalculateMemberStats($team);

        // Calculate active members count (members with deposits)
        $activeMembers = Cache::remember("active_members_deposit_" . auth()->id(), 1800, function () use ($team) {
            return DB::table('users')
                ->whereIn('id', $team)
                ->whereExists(function($query) {
                    $query->select(DB::raw(1))
                        ->from('deposits')
                        ->whereRaw('deposits.user_id = users.id')
                        ->where('deposits.status', 1);
                })
                ->count();
        });

        // Calculate email verified/unverified counts
        $emailVerifiedCount = Cache::remember("email_verified_" . auth()->id(), 1800, function () use ($team) {
            return User::whereIn('id', $team)->whereNotNull('email_verified_at')->count();
        });

        $emailUnverifiedCount = Cache::remember("email_unverified_" . auth()->id(), 1800, function () use ($team) {
            return User::whereIn('id', $team)->whereNull('email_verified_at')->count();
        });

        // Calculate KYC verified/unverified counts
        $kycVerifiedCount = Cache::remember("kyc_verified_" . auth()->id(), 1800, function () use ($team) {
            return User::whereIn('id', $team)->where('kyc_status', 1)->count();
        });

        $kycUnverifiedCount = Cache::remember("kyc_unverified_" . auth()->id(), 1800, function () use ($team) {
            return User::whereIn('id', $team)->whereNull('kyc_status')->count();
        });

        // Calculate ALL generations statistics (combined)
        $allGensStats = Cache::remember("all_gens_stats_" . auth()->id(), 1800, function () use ($team) {
            return $this->getAllGenerationsStats($team);
        });

        // Calculate total rebates earned (all 5 generations)
        // $totalRebatesEarned = Cache::remember("total_rebates_5gen_" . auth()->id(), 1800, function () use ($first, $second, $third, $fourth, $fifth) {
        //     $firstRebates = Transaction::whereIn('user_id', $first)->sum('amount') * (auth()->user()->first_rebate / 100);
        //     $secondRebates = Transaction::whereIn('user_id', $second)->sum('amount') * (auth()->user()->second_rebate / 100);
        //     $thirdRebates = Transaction::whereIn('user_id', $third)->sum('amount') * (auth()->user()->third_rebate / 100);
            
        //     // Assuming you have fourth_rebate and fifth_rebate columns, otherwise set to 0
        //     $fourthRebates = isset(auth()->user()->fourth_rebate) 
        //         ? Transaction::whereIn('user_id', $fourth)->sum('amount') * (auth()->user()->fourth_rebate / 100) 
        //         : 0;
        //     $fifthRebates = isset(auth()->user()->fifth_rebate) 
        //         ? Transaction::whereIn('user_id', $fifth)->sum('amount') * (auth()->user()->fifth_rebate / 100) 
        //         : 0;
            
        //     return $firstRebates + $secondRebates + $thirdRebates + $fourthRebates + $fifthRebates;
        // });
        $totalRebatesEarned = auth()->user()->rebates;

        return view('marketer-dashboard', array_merge(
            compact(
                'members',
                'team',
                'first',
                'second',
                'third',
                'fourth',
                'fifth',
                'memberStats',
                'activeMembers',
                'totalRebatesEarned',
                'emailVerifiedCount',
                'emailUnverifiedCount',
                'kycVerifiedCount',
                'kycUnverifiedCount'
            ),
            $allGensStats
        ));
    }

    /**
     * Show email verified members
     */
    public function emailVerified()
    {
        if (auth()->user()->type != 'marketer') {
            return redirect()->route('home')->with('error', 'Access denied.');
        }

        $cacheKey = 'marketer_team_5gen_' . auth()->id();
        $teamData = Cache::remember($cacheKey, 1800, function () {
            return $this->buildTeamArrays();
        });

        $members = User::whereIn('id', $teamData['team'])
            ->whereNotNull('email_verified_at')
            ->select('id', 'username', 'first_name', 'last_name', 'email', 'balance', 'email_verified_at', 'created_at')
            ->withCount('referrals')
            ->orderBy('created_at', 'desc')
            ->paginate(25);

        return view('marketer-members-list', [
            'members' => $members,
            'title' => 'Email Verified Members',
            'subtitle' => 'Team members who have verified their email addresses'
        ]);
    }

    /**
     * Show email unverified members
     */
    public function emailUnverified()
    {
        if (auth()->user()->type != 'marketer') {
            return redirect()->route('home')->with('error', 'Access denied.');
        }

        $cacheKey = 'marketer_team_5gen_' . auth()->id();
        $teamData = Cache::remember($cacheKey, 1800, function () {
            return $this->buildTeamArrays();
        });

        $members = User::whereIn('id', $teamData['team'])
            ->whereNull('email_verified_at')
            ->select('id', 'username', 'first_name', 'last_name', 'email', 'balance', 'created_at')
            ->withCount('referrals')
            ->orderBy('created_at', 'desc')
            ->paginate(25);

        return view('marketer-members-list', [
            'members' => $members,
            'title' => 'Email Unverified Members',
            'subtitle' => 'Team members who have not verified their email addresses'
        ]);
    }

    /**
     * Show KYC verified members
     */
    public function kycVerified()
    {
        if (auth()->user()->type != 'marketer') {
            return redirect()->route('home')->with('error', 'Access denied.');
        }

        $cacheKey = 'marketer_team_5gen_' . auth()->id();
        $teamData = Cache::remember($cacheKey, 1800, function () {
            return $this->buildTeamArrays();
        });

        $members = User::whereIn('id', $teamData['team'])
            ->where('kyc_status', 1)
            ->select('id', 'username', 'first_name', 'last_name', 'email', 'balance', 'kyc_status', 'created_at')
            ->withCount('referrals')
            ->orderBy('created_at', 'desc')
            ->paginate(25);

        // dd($members);
        return view('marketer-members-list', [
            'members' => $members,
            'title' => 'KYC Verified Members',
            'subtitle' => 'Team members who have completed KYC verification'
        ]);
    }

    /**
     * Show KYC unverified members
     */
    public function kycUnverified()
    {
        if (auth()->user()->type != 'marketer') {
            return redirect()->route('home')->with('error', 'Access denied.');
        }

        $cacheKey = 'marketer_team_5gen_' . auth()->id();
        $teamData = Cache::remember($cacheKey, 1800, function () {
            return $this->buildTeamArrays();
        });

        $members = User::whereIn('id', $teamData['team'])
            ->whereNull('kyc_status')
            ->select('id', 'username', 'first_name', 'last_name', 'email', 'balance', 'kyc_status', 'created_at')
            ->withCount('referrals')
            ->orderBy('created_at', 'desc')
            ->paginate(25);

        // dd($members);
        return view('marketer-members-list', [
            'members' => $members,
            'title' => 'KYC Unverified Members',
            'subtitle' => 'Team members who have not completed KYC verification'
        ]);
    }

    public function member($username)
    {
        if (auth()->user()->type != 'marketer') {
            return redirect()->route('home')->with('error', 'Access denied.');
        }

        $user = User::where('username', $username)->firstOrFail();

        $cacheKey = 'member_team_5gen_' . $user->id;
        $teamData = Cache::remember($cacheKey, 1800, function () use ($user) {
            return $this->buildMemberTeamArrays($user);
        });

        $first = $teamData['first'];
        $second = $teamData['second'];
        $third = $teamData['third'];
        $fourth = $teamData['fourth'];
        $fifth = $teamData['fifth'];
        $allTeam = $teamData['allTeam'];

        // Get paginated members for first 3 generations only (for display)
        $firstGenMembers = User::whereIn('id', $first)
            ->select('id', 'username', 'first_name', 'last_name', 'email', 'balance', 'rebates')
            ->withCount('referrals')
            ->paginate(25, ['*'], 'first_gen_page');
            
        $secondGenMembers = User::whereIn('id', $second)
            ->select('id', 'username', 'first_name', 'last_name', 'email', 'balance', 'rebates')
            ->withCount('referrals')
            ->paginate(25, ['*'], 'second_gen_page');
            
        $thirdGenMembers = User::whereIn('id', $third)
            ->select('id', 'username', 'first_name', 'last_name', 'email', 'balance', 'rebates')
            ->withCount('referrals')
            ->paginate(25, ['*'], 'third_gen_page');

        $allPageMemberIds = collect()
            ->merge($firstGenMembers->pluck('id'))
            ->merge($secondGenMembers->pluck('id'))
            ->merge($thirdGenMembers->pluck('id'))
            ->unique()
            ->toArray();
            
        $memberDetails = $this->batchCalculateMemberStats($allPageMemberIds);

        $userStatsCacheKey = 'user_stats_5gen_' . $user->id;
        $userStats = Cache::remember($userStatsCacheKey, 1800, function () use ($user) {
            return [
                'totalDeposits' => Deposit::where('user_id', $user->id)->where('status', 1)->sum('amount') ?? 0,
                'totalWithdrawals' => Withdrawal::where('user_id', $user->id)->where('status', 1)->sum('amount') ?? 0,
                'totalProfits' => 0
            ];
        });

        $firstGenStats = Cache::remember("member_gen_stats_first_{$user->id}", 1800, function () use ($first) {
            return $this->getGenerationStatsOptimized($first, 'first');
        });

        $secondGenStats = Cache::remember("member_gen_stats_second_{$user->id}", 1800, function () use ($second) {
            return $this->getGenerationStatsOptimized($second, 'second');
        });

        $thirdGenStats = Cache::remember("member_gen_stats_third_{$user->id}", 1800, function () use ($third) {
            return $this->getGenerationStatsOptimized($third, 'third');
        });

        $totalTeamSize = count($allTeam);

        return view('member-detail', array_merge(
            compact(
                'user',
                'first',
                'second',
                'third',
                'firstGenMembers',
                'secondGenMembers',
                'thirdGenMembers',
                'memberDetails',
                'totalTeamSize'
            ),
            $userStats,
            $firstGenStats,
            $secondGenStats,
            $thirdGenStats
        ));
    }

    /**
     * Build team arrays efficiently - NOW WITH 5 GENERATIONS
     */
    private function buildTeamArrays()
    {
        $team = [];
        $first = [];
        $second = [];
        $third = [];
        $fourth = [];
        $fifth = [];

        // First generation
        $firstGen = auth()->user()->referrals()->pluck('id')->toArray();
        $first = $firstGen;
        $team = array_merge($team, $firstGen);

        // Second generation
        if (!empty($firstGen)) {
            $secondGen = User::whereIn('referrer_id', $firstGen)->pluck('id')->toArray();
            $second = $secondGen;
            $team = array_merge($team, $secondGen);

            // Third generation
            if (!empty($secondGen)) {
                $thirdGen = User::whereIn('referrer_id', $secondGen)->pluck('id')->toArray();
                $third = $thirdGen;
                $team = array_merge($team, $thirdGen);

                // Fourth generation
                if (!empty($thirdGen)) {
                    $fourthGen = User::whereIn('referrer_id', $thirdGen)->pluck('id')->toArray();
                    $fourth = $fourthGen;
                    $team = array_merge($team, $fourthGen);

                    // Fifth generation
                    if (!empty($fourthGen)) {
                        $fifthGen = User::whereIn('referrer_id', $fourthGen)->pluck('id')->toArray();
                        $fifth = $fifthGen;
                        $team = array_merge($team, $fifthGen);
                    }
                }
            }
        }

        return compact('team', 'first', 'second', 'third', 'fourth', 'fifth');
    }

    /**
     * Build member team arrays efficiently - NOW WITH 5 GENERATIONS
     */
    private function buildMemberTeamArrays($user)
    {
        $first = [];
        $second = [];
        $third = [];
        $fourth = [];
        $fifth = [];
        $allTeam = [];

        // First generation
        $firstGen = $user->referrals()->pluck('id')->toArray();
        $first = $firstGen;
        $allTeam = array_merge($allTeam, $firstGen);

        // Second generation
        if (!empty($firstGen)) {
            $secondGen = User::whereIn('referrer_id', $firstGen)->pluck('id')->toArray();
            $second = $secondGen;
            $allTeam = array_merge($allTeam, $secondGen);

            // Third generation
            if (!empty($secondGen)) {
                $thirdGen = User::whereIn('referrer_id', $secondGen)->pluck('id')->toArray();
                $third = $thirdGen;
                $allTeam = array_merge($allTeam, $thirdGen);

                // Fourth generation
                if (!empty($thirdGen)) {
                    $fourthGen = User::whereIn('referrer_id', $thirdGen)->pluck('id')->toArray();
                    $fourth = $fourthGen;
                    $allTeam = array_merge($allTeam, $fourthGen);

                    // Fifth generation
                    if (!empty($fourthGen)) {
                        $fifthGen = User::whereIn('referrer_id', $fourthGen)->pluck('id')->toArray();
                        $fifth = $fifthGen;
                        $allTeam = array_merge($allTeam, $fifthGen);
                    }
                }
            }
        }

        return compact('first', 'second', 'third', 'fourth', 'fifth', 'allTeam');
    }

    /**
     * BATCH calculate stats for multiple members
     */
    private function batchCalculateMemberStats($memberIds)
    {
        if (empty($memberIds)) {
            return [];
        }

        $deposits = DB::table('deposits')
            ->whereIn('user_id', $memberIds)
            ->where('status', 1)
            ->select('user_id', DB::raw('SUM(amount) as total'))
            ->groupBy('user_id')
            ->pluck('total', 'user_id')
            ->toArray();

        $withdrawals = DB::table('withdrawals')
            ->whereIn('user_id', $memberIds)
            ->where('status', 1)
            ->select('user_id', DB::raw('SUM(amount) as total'))
            ->groupBy('user_id')
            ->pluck('total', 'user_id')
            ->toArray();

        $stats = [];
        foreach ($memberIds as $id) {
            $stats[$id] = [
                'deposits' => $deposits[$id] ?? 0,
                'withdrawals' => $withdrawals[$id] ?? 0,
                'profits' => 0,
                'team_size' => 0,
            ];
        }

        return $stats;
    }

    /**
     * Get ALL generations stats combined
     */
    private function getAllGenerationsStats($teamIds)
    {
        if (empty($teamIds)) {
            return [
                'allGensDeposits' => 0,
                'allGensWithdrawals' => 0,
                'allGensProfits' => 0,
            ];
        }

        $deposits = DB::table('deposits')
            ->whereIn('user_id', $teamIds)
            ->where('status', 1)
            ->sum('amount') ?? 0;

        $withdrawals = DB::table('withdrawals')
            ->whereIn('user_id', $teamIds)
            ->where('status', 1)
            ->sum('amount') ?? 0;

        return [
            'allGensDeposits' => $deposits,
            'allGensWithdrawals' => $withdrawals,
            'allGensProfits' => 0,
        ];
    }

    /**
     * Get optimized statistics for a generation
     */
    private function getGenerationStatsOptimized($generationIds, $genName)
    {
        if (empty($generationIds)) {
            return [
                "{$genName}GenDeposits" => 0,
                "{$genName}GenWithdrawals" => 0,
                "{$genName}GenProfits" => 0,
            ];
        }

        $deposits = DB::table('deposits')
            ->whereIn('user_id', $generationIds)
            ->where('status', 1)
            ->sum('amount') ?? 0;

        $withdrawals = DB::table('withdrawals')
            ->whereIn('user_id', $generationIds)
            ->where('status', 1)
            ->sum('amount') ?? 0;

        return [
            "{$genName}GenDeposits" => $deposits,
            "{$genName}GenWithdrawals" => $withdrawals,
            "{$genName}GenProfits" => 0,
        ];
    }

    /**
     * Clear cache for marketer
     */
    public function clearCache()
    {
        $patterns = [
            'marketer_team_5gen_',
            'active_members_deposit_',
            'email_verified_',
            'email_unverified_',
            'kyc_verified_',
            'kyc_unverified_',
            'all_gens_stats_',
            'total_rebates_5gen_',
        ];

        foreach ($patterns as $pattern) {
            Cache::forget($pattern . auth()->id());
        }

        return back()->with('success', 'Cache cleared successfully!');
    }
}