<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\BinaryLedger;
use App\Models\Plan;
use App\Models\UserBinaryCarry;
use Illuminate\Contracts\View\View;

class PlanController extends Controller
{
    public function index(): View
    {
        $user = auth()->user();
        $carry = UserBinaryCarry::query()->firstOrCreate(['user_id' => $user->id]);

        $leftJoiningBv = $this->legBv($user->id, 'left', ['joining', 'reversal_joining']);
        $rightJoiningBv = $this->legBv($user->id, 'right', ['joining', 'reversal_joining']);
        $leftRepurchaseBv = $this->legBv($user->id, 'left', ['repurchase', 'reversal_repurchase']);
        $rightRepurchaseBv = $this->legBv($user->id, 'right', ['repurchase', 'reversal_repurchase']);

        return view('user.plans', [
            'plans' => Plan::query()
                ->where('is_active', true)
                ->orderBy('sort_order')
                ->orderBy('id')
                ->get(),
            'currentPlan' => Plan::query()->whereKey($user->current_plan_id)->first(),
            'settings' => [
                'pairing_ratio' => (string) setting('pairing_ratio', '1:1'),
                'joining_pair_value' => (float) setting('joining_pair_value', 0),
                'repurchase_pair_rate' => (float) setting('pair_rate', 0),
                'daily_capping' => (float) setting('daily_capping', 0),
                'hold_days' => (int) setting('hold_days', 0),
            ],
            'binary' => [
                'joining_left_bv' => $leftJoiningBv,
                'joining_right_bv' => $rightJoiningBv,
                'joining_matchable' => min($leftJoiningBv, $rightJoiningBv),
                'repurchase_left_bv' => $leftRepurchaseBv,
                'repurchase_right_bv' => $rightRepurchaseBv,
                'repurchase_matchable' => min($leftRepurchaseBv, $rightRepurchaseBv),
                'carry_joining_left' => (float) $carry->joining_left,
                'carry_joining_right' => (float) $carry->joining_right,
                'carry_repurchase_left' => (float) $carry->repurchase_left,
                'carry_repurchase_right' => (float) $carry->repurchase_right,
            ],
            'links' => [
                'left' => url('/register-user').'?sponsor='.$user->referral_code.'&leg=left',
                'right' => url('/register-user').'?sponsor='.$user->referral_code.'&leg=right',
                'auto' => url('/register-user').'?sponsor='.$user->referral_code.'&leg=auto',
            ],
        ]);
    }

    /**
     * @param array<int, string> $ledgerTypes
     */
    private function legBv(int $userId, string $leg, array $ledgerTypes): float
    {
        return (float) BinaryLedger::query()
            ->where('beneficiary_user_id', $userId)
            ->where('leg', $leg)
            ->whereIn('ledger_type', $ledgerTypes)
            ->selectRaw("COALESCE(SUM(CASE WHEN direction = 'credit' THEN units ELSE -units END), 0) as total")
            ->value('total');
    }
}
