<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\BalanceLog;
use App\Models\IncomeHistory;
use App\Models\SmartLeadershipReward;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class SmartLeadershipController extends Controller
{
    private const REQUIRED_ACTIVE_REFERRALS = 12;
    private const REWARD_AMOUNT = 120.0;

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

        $activeReferralsCount = $this->activeDirectReferralsCount($user);

        $achievedLevel = SmartLeadershipReward::where('user_id', $user->id)->count();

        $currentLevel = intdiv($activeReferralsCount, self::REQUIRED_ACTIVE_REFERRALS);
        $hasNewAchievement = $currentLevel > $achievedLevel;

        $remaining = ($currentLevel + 1) * self::REQUIRED_ACTIVE_REFERRALS - $activeReferralsCount;

        $progressPercent = min(100, intval(($activeReferralsCount % self::REQUIRED_ACTIVE_REFERRALS) / self::REQUIRED_ACTIVE_REFERRALS * 100));

        return view('user.smart-leadership', compact(
            'activeReferralsCount',
            'achievedLevel',
            'currentLevel',
            'hasNewAchievement',
            'remaining',
            'progressPercent'
        ));
    }

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

        $claimedLevel = DB::transaction(function () use ($user) {
            $lockedUser = User::query()
                ->whereKey($user->id)
                ->lockForUpdate()
                ->firstOrFail();

            $activeReferralsCount = $this->activeDirectReferralsCount($lockedUser);
            $achievedLevel = SmartLeadershipReward::where('user_id', $lockedUser->id)->count();
            $currentLevel = intdiv($activeReferralsCount, self::REQUIRED_ACTIVE_REFERRALS);

            $newLevel = $achievedLevel + 1;

            if ($currentLevel < $newLevel) {
                return null;
            }

            SmartLeadershipReward::create([
                'user_id' => $lockedUser->id,
                'level'   => $newLevel,
                'amount'  => self::REWARD_AMOUNT,
            ]);

            $lockedUser->increment('balance', self::REWARD_AMOUNT);

            BalanceLog::create([
                'user_id' => $lockedUser->id,
                'amount'  => self::REWARD_AMOUNT,
            ]);

            IncomeHistory::create([
                'user_id'     => $lockedUser->id,
                'source'      => 'smart_leadership',
                'amount'      => self::REWARD_AMOUNT,
                'description' => 'অভিনন্দন! আপনি '.$this->ordinal($newLevel).' বারের মতো ভিশনারি ক্যাপ্টেন লিডারশিপ এচিভ করে ১২০৳ পুরস্কার পেয়েছেন।',
            ]);

            return $newLevel;
        });

        if ($claimedLevel !== null) {
            return redirect()->back()->with('success', 'অভিনন্দন! আপনি ১২০৳ পুরস্কার পেয়েছেন।');
        }

        return redirect()->back()->with('error', 'দুঃখিত! আপনি এখনো লিডারশিপ এচিভ করেননি।');
    }

    public function history()
    {
        $rewards = SmartLeadershipReward::where('user_id', auth()->id())
            ->orderByDesc('claimed_at')
            ->get();

        return view('user.leadership.smart.history', compact('rewards'));
    }

    private function activeDirectReferralsCount(User $user): int
    {
        $code = trim((string) ($user->referral_code ?? ''));
        if ($code === '') {
            return 0;
        }

        $idAsString = (string) $user->id;

        return User::query()
            ->where(function ($q) use ($code, $idAsString) {
                $q->where('referred_by', $code)
                    ->orWhere('referred_by', $idAsString);
            })
            ->where('is_active', 1)
            ->count();
    }

    private function ordinal($number)
    {
        $bn = ['১ম', '২য়', '৩য়', '৪র্থ', '৫ম', '৬ষ্ঠ', '৭ম', '৮ম', '৯ম', '১০ম', '১১তম', '১২তম', '১৩তম', '১৪তম', '১৫তম'];
        return $bn[$number - 1] ?? $number.'তম';
    }
}
