<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\ActivationRequest;
use App\Models\GeneralSetting;
use App\Services\AccountActivationService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class ActivationRequestController extends Controller
{
    private AccountActivationService $accountActivationService;

    public function __construct(AccountActivationService $accountActivationService)
    {
        $this->accountActivationService = $accountActivationService;
    }

    public function form(): View|RedirectResponse
    {
        $user = auth()->user();

        if ((int) $user->is_active === 1) {
            return redirect()->route('dashboard');
        }

        $settings = $this->settings();

        return view('user.activation.form', [
            'verifyFee' => round((float) ($settings->verify_fee ?? 0), 2),
            'voucherBalance' => round((float) ($user->voucher_balance ?? 0), 2),
            'hasPendingRequest' => ActivationRequest::query()
                ->where('user_id', $user->id)
                ->where('status', 'pending')
                ->exists(),
        ]);
    }

    public function submit(Request $request): RedirectResponse
    {
        $user = auth()->user();

        if ((int) $user->is_active === 1) {
            return redirect()->route('dashboard');
        }

        $pending = ActivationRequest::query()
            ->where('user_id', $user->id)
            ->where('status', 'pending')
            ->first();

        if ($pending) {
            return redirect()->route('activation.success');
        }

        $request->validate([
            'mobile' => ['required', 'string', 'min:10', 'max:20'],
            'referral_code' => ['required', 'string', 'max:50'],
        ], [
            'referral_code.required' => 'রেফার কোড অবশ্যই দিতে হবে।',
        ]);

        $inputRef = strtolower(trim((string) $request->referral_code));
        $myRef = $user->referral_code ? strtolower(trim($user->referral_code)) : null;

        if ($myRef && $inputRef !== $myRef) {
            return back()
                ->withErrors(['referral_code' => 'রেফার কোড ভুল। শুধু আপনার নিজের রেফার কোডই ব্যবহার করতে পারবেন।'])
                ->withInput();
        }

        if (!$myRef) {
            return back()
                ->withErrors(['referral_code' => 'আপনার একাউন্টে কোনো রেফার কোড সেট নেই। তাই এখানে কিছু লিখবেন না।'])
                ->withInput();
        }

        ActivationRequest::create([
            'user_id' => $user->id,
            'mobile' => $request->mobile,
            'referral_code' => trim((string) $request->referral_code),
            'status' => 'pending',
        ]);

        return redirect()->route('activation.success');
    }

    public function verifyWithVoucher(): RedirectResponse
    {
        $user = auth()->user();

        if ((int) $user->is_active === 1) {
            return redirect()->route('dashboard');
        }

        $amount = round((float) ($this->settings()->verify_fee ?? 0), 2);

        if ($amount <= 0) {
            return back()->withErrors([
                'voucher' => 'ভেরিফিকেশন ফি এখনো সেট করা হয়নি। পরে আবার চেষ্টা করুন।',
            ]);
        }

        $result = $this->accountActivationService->activateWithVoucher($user, $amount);

        if (($result['status'] ?? null) === 'already_active') {
            return redirect()->route('dashboard')->with('success', 'আপনার একাউন্ট আগেই ভেরিফাইড আছে।');
        }

        if (($result['status'] ?? null) === 'insufficient_balance') {
            return back()->withErrors([
                'voucher' => 'ভাউচার ব্যালেন্স পর্যাপ্ত নয়। আরও ৳' . number_format((float) ($result['shortfall'] ?? 0), 2) . ' যোগ করুন।',
            ]);
        }

        return redirect()->route('dashboard')->with(
            'success',
            'অভিনন্দন! আপনার একাউন্ট ভাউচার থেকে সফলভাবে ভেরিফাই হয়েছে।'
        );
    }

    public function success(): View|RedirectResponse
    {
        $user = auth()->user();

        if ((int) $user->is_active === 1) {
            return redirect()->route('dashboard');
        }

        return view('user.activation.success');
    }

    private function settings(): GeneralSetting
    {
        return GeneralSetting::firstOrCreate(
            ['id' => 1],
            [
                'verify_fee' => 300,
                'bondhonpay_api_key' => '',
            ]
        );
    }
}
