<?php

namespace App\Http\Controllers;

use App\Models\Loan;
use App\Models\LoanInstallment;
use App\Models\MobileBankMethod;
use App\Models\BankMethod;
use App\Models\BellNotification;
use App\Events\LoanInstallmentSubmitted; // 🔔 নতুন Event
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoanInstallmentController extends Controller
{
    /** latest paid installments list (সকল user এর) */
    public function paidIndex()
    {
        $installments = LoanInstallment::with(['loan.user'])
            ->where('status', 'paid')
            ->orderByDesc('paid_at')
            ->orderByDesc('id')
            ->paginate(30);

        return view('backend.loans.installments_paid', compact('installments'));
    }

    // জমা দিন (running loans → upcoming installments)
    public function index()
    {
        $userId = Auth::id();

        $installments = LoanInstallment::with('loan')
            ->whereHas('loan', fn ($q) => $q->where('user_id', $userId)->where('status', 'running'))
            ->whereIn('status', ['upcoming', 'submitted'])
            ->orderBy('due_date')
            ->get();

        return view('frontend.loan.installments-index', compact('installments'));
    }

    /** pay form + method list (mobile + bank) */
    public function payForm(LoanInstallment $installment)
    {
        $this->authorizeInstallment($installment);

        $loan   = $installment->loan;
        $amount = $installment->amount;

        // deposit / withdraw এর মত dynamic method list
        $mobileMethods = MobileBankMethod::where('status', 1)
            ->orderBy('sort_order')
            ->orderBy('name')
            ->get();

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

        return view('frontend.loan.installments-pay', compact(
            'loan',
            'installment',
            'amount',
            'mobileMethods',
            'bankMethods'
        ));
    }

    // user submit → mark as "submitted" (pending admin review)
    public function payStore(Request $request, LoanInstallment $installment)
    {
        $this->authorizeInstallment($installment);

        if (in_array($installment->status, ['submitted', 'paid'])) {
            return redirect()->route('loan.installments.success', $installment);
        }

        // 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:191',
        ]);

        // কমপক্ষে installment amount দিতে হবে
        if ((int) $request->amount < (int) $installment->amount) {
            return back()->withErrors([
                'amount' => 'কমপক্ষে ' . $installment->amount . ' টাকা দিতে হবে।',
            ])->withInput();
        }

        // update installment
        $installment->update([
            'payment_method' => $request->method,           // mobile:bkash / bank:ab-bank
            'payment_trx_id' => $request->transaction_id,
            'paid_amount'    => $request->amount,
            'status'         => 'submitted',                // admin approve করলে "paid" হবে
            'paid_at'        => now(),
        ]);

        // ===== Notification create (same ভাবে) =====
        $user   = $installment->loan?->user ?? Auth::user();
        $method = $request->method;
        $methodLabel = $method;

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

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

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

        BellNotification::create([
            'user_id' => $user?->id,
            'title'   => 'Loan Installment Payment Submitted',
            'status'  => 'unread',
            'type'    => 'loan_installment',
            'amount'  => $request->amount,
            'message' =>
                "আপনার লোন কিস্তি {$request->amount} টাকা পরিশোধের অনুরোধ সাবমিট হয়েছে। " .
                "পেমেন্ট মেথড: {$methodLabel}, ট্রানজেকশন আইডি: {$request->transaction_id}. " .
                "অনুগ্রহ করে অ্যাডমিন অনুমোদনের জন্য অপেক্ষা করুন।",
            'read_at' => null,
        ]);
        // ===========================================

        // 🔥 Event fire (same স্টাইলে)
        event(new LoanInstallmentSubmitted($installment->fresh(['loan.user'])));

        return redirect()->route('loan.installments.success', $installment);
    }

    // Success / receipt page
    public function success(LoanInstallment $installment)
    {
        $this->authorizeInstallment($installment);
        $loan = $installment->loan;

        return view('frontend.loan.installments-success', compact('loan', 'installment'));
    }

    protected function authorizeInstallment(LoanInstallment $installment)
    {
        // abort_if(!$installment->loan || $installment->loan->user_id !== Auth::id(), 403);
    }
}
