<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\BinaryLedger;
use App\Models\Rank;
use App\Models\RankHistory;
use App\Models\User;
use Illuminate\Contracts\View\View;

class RankController extends Controller
{
    public function index(): View
    {
        $user = auth()->user()->load('currentRank');

        $leftBv = (float) BinaryLedger::query()
            ->where('beneficiary_user_id', $user->id)
            ->where('leg', 'left')
            ->where('ledger_type', 'repurchase')
            ->selectRaw("COALESCE(SUM(CASE WHEN direction='credit' THEN units ELSE -units END),0) as total")
            ->value('total');

        $rightBv = (float) BinaryLedger::query()
            ->where('beneficiary_user_id', $user->id)
            ->where('leg', 'right')
            ->where('ledger_type', 'repurchase')
            ->selectRaw("COALESCE(SUM(CASE WHEN direction='credit' THEN units ELSE -units END),0) as total")
            ->value('total');

        $weakLegBv = min($leftBv, $rightBv);
        $teamTurnover = max(0, $leftBv) + max(0, $rightBv);
        $activeDirects = User::query()
            ->where('sponsor_id', $user->id)
            ->where('status', 'active')
            ->count();

        $ranks = Rank::query()
            ->where('is_active', true)
            ->orderBy('priority')
            ->get();

        $progressRows = $ranks->map(function (Rank $rank) use ($weakLegBv, $teamTurnover, $activeDirects) {
            $weakPct = $rank->required_weak_leg_bv > 0
                ? min(100, ($weakLegBv / (float) $rank->required_weak_leg_bv) * 100)
                : 100;
            $turnoverPct = $rank->required_team_turnover > 0
                ? min(100, ($teamTurnover / (float) $rank->required_team_turnover) * 100)
                : 100;
            $directPct = $rank->required_active_directs > 0
                ? min(100, ($activeDirects / (float) $rank->required_active_directs) * 100)
                : 100;
            $overall = min($weakPct, $turnoverPct, $directPct);

            return [
                'rank' => $rank,
                'weak_pct' => round($weakPct, 1),
                'turnover_pct' => round($turnoverPct, 1),
                'direct_pct' => round($directPct, 1),
                'overall_pct' => round($overall, 1),
                'is_qualified' => $weakPct >= 100 && $turnoverPct >= 100 && $directPct >= 100,
            ];
        });

        $currentPriority = (int) ($user->currentRank?->priority ?? 0);
        $nextRank = $ranks->first(fn (Rank $rank) => (int) $rank->priority > $currentPriority);

        $history = RankHistory::query()
            ->where('user_id', $user->id)
            ->with(['fromRank:id,name', 'toRank:id,name'])
            ->latest('run_date')
            ->latest('id')
            ->limit(30)
            ->get();

        return view('user.rank', [
            'member' => $user,
            'leftBv' => $leftBv,
            'rightBv' => $rightBv,
            'weakLegBv' => $weakLegBv,
            'teamTurnover' => $teamTurnover,
            'activeDirects' => $activeDirects,
            'progressRows' => $progressRows,
            'nextRank' => $nextRank,
            'history' => $history,
        ]);
    }
}
