<?php
 
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Loan;
use App\Models\LoanDeposit;
use Illuminate\Http\Request;

class AdminLoanController extends Controller
{
    public function index()
    {
        $loans = Loan::with('user', 'deposits')->latest()->paginate(20);

        return view('admin.loans.index', compact('loans'));
    }

    public function show(Loan $loan)
    {
        $loan->load('user', 'installments', 'deposits');

        return view('admin.loans.show', compact('loan'));
    }

    /**
     * Loan approve করলে:
     *  - status => running
     *  - approved_at set
     *  - user->balance += loan amount + approved deposits
     */
    public function approve(Loan $loan)
    {
        // যদি আগেই approve বা reject হয়ে থাকে, আবার কিছু না করি
        if ($loan->status === 'running') {
            return back()->with('success', 'Loan is already approved.');
        }

        if ($loan->status === 'rejected') {
            return back()->with('success', 'Loan is already rejected.');
        }

        $user = $loan->user;

        if ($user) {
            // পুরো approved জামানত কত – ধরলাম সব একবারেই ফেরত দিবে
            $approvedDeposit = $loan->deposits()
                ->where('status', 'approved')
                ->sum('amount');

            // loan amount + approved deposit দুটোই credit হবে
            $creditAmount = $loan->amount + $approvedDeposit;

            // balance null থাকলে 0 ধরে নিবো (পুরনো data সুরক্ষিত)
            $currentBalance = $user->balance ?? 0;

            $user->balance = $currentBalance + $creditAmount;
            $user->save();
        }

        $loan->update([
            'status'      => 'running',
            'approved_at' => now(),
        ]);

        return back()->with('success', 'Loan approved & user balance updated.');
    }

    public function reject(Loan $loan)
    {
        // reject করলে শুধু status change – balance touch করবো না
        if ($loan->status === 'rejected') {
            return back()->with('success', 'Loan already rejected.');
        }

        $loan->update([
            'status' => 'rejected',
        ]);

        return back()->with('success', 'Loan rejected');
    }

    /**
     * Admin জামানত approve করলে:
     *  - deposit.status = approved
     *  - loan.status pending_deposit হলে => pending_approval
     * এখানে balance সরাসরি বদলাই না,
     * approve() করার সময় একসাথে যোগ হবে।
     */
    public function approveDeposit(LoanDeposit $deposit)
    {
        $deposit->update(['status' => 'approved']);

        // loan status adjust
        $loan = $deposit->loan;
        if ($loan && $loan->status === 'pending_deposit') {
            $loan->update(['status' => 'pending_approval']);
        }

        return back()->with('success', 'Deposit approved');
    }

    public function rejectDeposit(LoanDeposit $deposit)
    {
        $deposit->update(['status' => 'rejected']);

        return back()->with('success', 'Deposit rejected');
    }
}
