<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use App\Models\SalaryClaim;
use Illuminate\Support\Collection;

class SalaryController extends Controller
{
    public function show()
    {
        $user = Auth::user();

        $lastClaim = SalaryClaim::where('user_id', $user->id)->latest()->first();

        // Step 1: Active referrals directly under user
        $step1Users = $this->downlineQueryFromUsers(collect([$user]))
                          ->where('is_active', 1)
                          ->when($lastClaim, function($q) use ($lastClaim) {
                              return $q->where('id', '>', $lastClaim->last_step1_user_id ?? 0);
                          })
                          ->get();
        $step1Count = $step1Users->count();

        // Step 2: Referrals under step1 users
        $step2Users = $this->downlineQueryFromUsers($step1Users)
                          ->where('is_active', 1)
                          ->when($lastClaim, function($q) use ($lastClaim) {
                              return $q->where('id', '>', $lastClaim->last_step2_user_id ?? 0);
                          })
                          ->get();
        $step2Count = $step2Users->count();

        $canClaim = $step1Count >= 12 && $step2Count >= 50;

        return view('salary.index', compact('step1Count', 'step2Count', 'canClaim'));
    }

    public function claim()
    {
        $user = Auth::user();

        $lastClaim = SalaryClaim::where('user_id', $user->id)->latest()->first();

        $step1Users = $this->downlineQueryFromUsers(collect([$user]))
                          ->where('is_active', 1)
                          ->when($lastClaim, function($q) use ($lastClaim) {
                              return $q->where('id', '>', $lastClaim->last_step1_user_id ?? 0);
                          })
                          ->get();
        $step1Count = $step1Users->count();

        $step2Users = $this->downlineQueryFromUsers($step1Users)
                          ->where('is_active', 1)
                          ->when($lastClaim, function($q) use ($lastClaim) {
                              return $q->where('id', '>', $lastClaim->last_step2_user_id ?? 0);
                          })
                          ->get();
        $step2Count = $step2Users->count();

        if ($step1Count >= 12 && $step2Count >= 50) {
            // Bonus
            $user->increment('balance', 2000);

            SalaryClaim::create([
                'user_id' => $user->id,
                'last_step1_user_id' => $step1Users->last()->id,
                'last_step2_user_id' => $step2Users->last()->id,
            ]);

            return redirect()->back()->with('success', 'অভিনন্দন! আপনি সফলভাবে ২০০০৳ বেতন পেয়েছেন।');
        }

        return redirect()->back()->with('error', 'আপনার টার্গেট এখনো পূর্ণ হয়নি।');
    }

    public function showStep1Members(Request $request)
    {
        $user = auth()->user();
        $search = $request->input('search');
        $lastClaim = SalaryClaim::where('user_id', $user->id)->latest()->first();

        $referrals = $this->downlineQueryFromUsers(collect([$user]))
                         ->where('is_active', 1)
                         ->when($lastClaim, function($q) use ($lastClaim) {
                             return $q->where('id', '>', $lastClaim->last_step1_user_id ?? 0);
                         })
                         ->get();

        if ($search) {
            $referrals = $referrals->filter(function ($ref) use ($search) {
                return stripos($ref->referral_code, $search) !== false ||
                       stripos($ref->mobile, $search) !== false;
            });
        }

        $level = 1;
        return view('referrals.active-list', compact('referrals', 'level', 'search'));
    }

    public function showStep2Members(Request $request)
    {
        $user = auth()->user();
        $search = $request->input('search');
        $lastClaim = SalaryClaim::where('user_id', $user->id)->latest()->first();

        $step1Users = $this->downlineQueryFromUsers(collect([$user]))
                        ->where('is_active', 1)
                        ->when($lastClaim, function($q) use ($lastClaim) {
                            return $q->where('id', '>', $lastClaim->last_step1_user_id ?? 0);
                        })
                        ->get();

        $referrals = $this->downlineQueryFromUsers($step1Users)
                         ->where('is_active', 1)
                         ->when($lastClaim, function($q) use ($lastClaim) {
                             return $q->where('id', '>', $lastClaim->last_step2_user_id ?? 0);
                         })
                         ->get();

        if ($search) {
            $referrals = $referrals->filter(function ($ref) use ($search) {
                return stripos($ref->referral_code, $search) !== false ||
                       stripos($ref->mobile, $search) !== false;
            });
        }

        $level = 2;
        return view('referrals.active-list', compact('referrals', 'level', 'search'));
    }

    private function downlineQueryFromUsers(Collection $parents)
    {
        $parentCodes = $parents->pluck('referral_code')
            ->map(fn($v) => trim((string) $v))
            ->filter(fn($v) => $v !== '')
            ->unique()
            ->values();

        $parentIds = $parents->pluck('id')
            ->map(fn($v) => trim((string) $v))
            ->filter(fn($v) => $v !== '')
            ->unique()
            ->values();

        return User::query()->where(function ($q) use ($parentCodes, $parentIds) {
            if ($parentCodes->isNotEmpty()) {
                $q->whereIn('referred_by', $parentCodes->all());
            }

            if ($parentIds->isNotEmpty()) {
                $q->orWhereIn('referred_by', $parentIds->all());
            }
        });
    }
}
