<?php 

namespace App\Http\Controllers;

use App\Models\DepositRule;
use App\Models\Loan;
use App\Models\LoanDeposit;
use App\Models\MobileBankMethod;
use App\Models\BankMethod;
use App\Models\BellNotification;
use App\Events\LoanDepositSubmitted; // 🔔 আমাদের নতুন Event
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoanDepositController extends Controller
{
    /** ইউজার নিজের লোন কিনা চেক */
    protected function authorizeLoan(Loan $loan): void
    {
        // চাইলে এখানে আবার authorize চালু করতে পারো
        // abort_if($loan->user_id !== Auth::id(), 403);
    }

    /** (optional) যদি লোন সিলেক্ট পেজ দরকার হয় */
    public function selectLoan()
    {
        $userId = Auth::id();

        $loans = Loan::where('user_id', $userId)
            ->whereIn('status', ['summary_confirmed', 'nid_uploaded', 'pending_deposit', 'pending_approval'])
            ->orderByDesc('created_at')
            ->get();

        return view('frontend.loan.deposit-select', compact('loans'));
    }

    /** Method list (mobile + bank) */
    public function method(Loan $loan)
    {
        $this->authorizeLoan($loan);

        $depositAmount = $this->calculateDeposit($loan->amount);

        $mobileMethods = MobileBankMethod::where('status', 1)
            ->orderBy('name')
            ->get();

        $bankMethods = BankMethod::where('status', 1)
            ->orderBy('bank_name')
            ->get();

        return view('frontend.loan.deposit-method', compact(
            'loan',
            'depositAmount',
            'mobileMethods',
            'bankMethods'
        ));
    }

    /** নির্দিষ্ট gateway form (mobile:slug / bank:slug) */
    public function gatewayForm(Loan $loan, string $method)
    {
        $this->authorizeLoan($loan);

        // method = "mobile:bkash" অথবা "bank:ab-bank"
        [$type, $slug] = explode(':', $method, 2);

        $methodType    = $type === 'bank' ? 'bank' : 'mobile';
        $accountHolder = null;
        $branchName    = null;
        $pm            = null;

        if ($methodType === 'mobile') {
            $pm = MobileBankMethod::where('slug', $slug)
                ->where('status', 1)
                ->firstOrFail();

            $methodName  = $pm->name;
            $agentNumber = $pm->account_number;
        } else {
            $pm = BankMethod::where('slug', $slug)
                ->where('status', 1)
                ->firstOrFail();

            $methodName   = $pm->bank_name;
            $agentNumber  = $pm->account_number;
            $accountHolder= $pm->account_holder;
            $branchName   = $pm->branch_name;
        }

        $depositAmount = $this->calculateDeposit($loan->amount);

        return view('frontend.loan.deposit-gateway', [
            'loan'          => $loan,
            'depositAmount' => $depositAmount,
            'methodKey'     => $method,        // mobile:bkash / bank:ab-bank
            'methodName'    => $methodName,
            'methodType'    => $methodType,    // blade এ mobile/bank চেক করার জন্য
            'agentNumber'   => $agentNumber,   // অ্যাকাউন্ট নম্বর
            'accountHolder' => $accountHolder, // শুধুই bank এর ক্ষেত্রে
            'branchName'    => $branchName,    // শুধুই bank এর ক্ষেত্রে
            'logo'          => $pm->logo ?? null,
        ]);
    }

    /** ডিপোজিট সেভ */
    public function store(Request $request, Loan $loan)
    {
        $this->authorizeLoan($loan);

        // allow method list (mobile:slug + bank:slug)
        $mobileKeys = MobileBankMethod::where('status', 1)
            ->pluck('slug')
            ->map(fn ($s) => 'mobile:' . $s);

        $bankKeys = BankMethod::where('status', 1)
            ->pluck('slug')
            ->map(fn ($s) => 'bank:' . $s);

        $allKeys = $mobileKeys->merge($bankKeys);

        $request->validate([
            'method'         => ['required', 'in:' . $allKeys->implode(',')],
            'amount'         => ['required', 'integer', 'min:1'],
            'transaction_id' => ['required', 'string', 'max:255'],
        ]);

        // নিরাপত্তার জন্য amount মিলিয়ে দেখি
        $calculated = $this->calculateDeposit($loan->amount);
        if ((int) $request->amount !== (int) $calculated) {
            return back()->withErrors([
                'amount' => 'ডিপোজিট অ্যামাউন্ট সঠিক নয়। আবার চেষ্টা করুন।',
            ])->withInput();
        }

        // ডিপোজিট সেভ
        $deposit = LoanDeposit::create([
            'loan_id'        => $loan->id,
            'method'         => $request->method,  // mobile:bkash / bank:ab-bank
            'amount'         => $calculated,
            'transaction_id' => $request->transaction_id,
        ]);

        // লোনের স্ট্যাটাস আপডেট
        $loan->update(['status' => 'pending_deposit']);

        // ===== Notification create =====
        $methodLabel = $request->method;

        if (str_starts_with($request->method, 'mobile:')) {
            $slug = substr($request->method, strlen('mobile:'));
            $pm   = MobileBankMethod::where('slug', $slug)->first();

            if ($pm) {
                $methodLabel = $pm->name . ' (' . $pm->account_number . ')';
            } else {
                $methodLabel = 'Mobile Payment';
            }
        } elseif (str_starts_with($request->method, 'bank:')) {
            $slug = substr($request->method, strlen('bank:'));
            $pm   = BankMethod::where('slug', $slug)->first();

            if ($pm) {
                $methodLabel = $pm->bank_name . ' (' . $pm->account_number . ')';
            } else {
                $methodLabel = 'Bank Deposit';
            }
        }

        BellNotification::create([
            'user_id' => $loan->user_id,
            'title'   => 'New Loan Deposit Submitted',
            'status'  => 'unread',
            'type'    => 'loan_deposit',
            'amount'  => $deposit->amount,
            'message' =>
                "আপনার জামানত {$deposit->amount} টাকা সাবমিট হয়েছে। " .
                "পেমেন্ট মেথড: {$methodLabel}, ট্রানজেকশন আইডি: {$deposit->transaction_id}.",
            'read_at' => null,
        ]);
        // ================================

        // 🔥 Event fire (BankAddMoney demo এর মত)
        event(new LoanDepositSubmitted($deposit));

        return redirect()->route('loan.deposit.success', [
            'loan'    => $loan->id,
            'deposit' => $deposit->id,
        ]);
    }

    /** Success page */
    public function success(Loan $loan, LoanDeposit $deposit)
    {
        $this->authorizeLoan($loan);

        $pm = null;
        $methodType = 'mobile';

        if (str_starts_with($deposit->method, 'mobile:')) {
            $slug       = substr($deposit->method, strlen('mobile:'));
            $pm         = MobileBankMethod::where('slug', $slug)->first();
            $methodType = 'mobile';
        } elseif (str_starts_with($deposit->method, 'bank:')) {
            $slug       = substr($deposit->method, strlen('bank:'));
            $pm         = BankMethod::where('slug', $slug)->first();
            $methodType = 'bank';
        }

        return view('frontend.loan.deposit-success', [
            'loan'       => $loan,
            'deposit'    => $deposit,
            'pm'         => $pm,
            'methodType' => $methodType,
        ]);
    }

    /** জামানত ক্যালকুলেশন */
    protected function calculateDeposit(int $loanAmount): int
    {
        $rule = DepositRule::where('is_active', 1)
            ->where('min_amount', '<=', $loanAmount)
            ->where(function ($q) use ($loanAmount) {
                $q->whereNull('max_amount')
                  ->orWhere('max_amount', '>=', $loanAmount);
            })
            ->orderByDesc('min_amount')
            ->first();

        if (! $rule) {
            return 500; // fallback
        }

        if ($rule->calc_type === 'flat') {
            return (int) round($rule->value);
        }

        return (int) round($loanAmount * ($rule->value / 100));
    }
}
