<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\LoanApplication;
use App\Models\LoanRepayment;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class LoanAdminController extends Controller
{
    public function index(Request $request)
    {
        $status = $request->get('status');
        $loans = LoanApplication::when($status, fn($q)=>$q->where('status',$status))
            ->with('user')
            ->latest()
            ->paginate(20)->withQueryString();

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

    public function show(LoanApplication $loan)
    {
        $loan->load('user','repayments');
        return view('admin.loans.show', compact('loan'));
    }

    public function approve(Request $request, LoanApplication $loan)
    {
        abort_if($loan->status !== 'pending', 400, 'Already processed.');

        DB::transaction(function () use ($loan) {
            /** @var User $user */
            $user = User::whereKey($loan->user_id)->lockForUpdate()->first();

            // 1) balance credit
            $user->increment('balance', $loan->loan_amount);

            // 2) approve status
            $loan->update(['status' => 'approved']);

            // 3) generate equal repayments
            $perMonth = round($loan->estimated_total / $loan->loan_period, 2);
            $start = Carbon::today()->addMonth(); // first due next month
            for ($i=0; $i<$loan->loan_period; $i++) {
                LoanRepayment::create([
                    'loan_application_id' => $loan->id,
                    'due_date' => $start->copy()->addMonths($i)->toDateString(),
                    'amount'   => $perMonth,
                    'status'   => 'due',
                ]);
            }
        });

        return back()->with('success','Loan approved & schedule created, amount credited to user balance.');
    }

    public function reject(Request $request, LoanApplication $loan)
    {
        abort_if($loan->status !== 'pending', 400, 'Already processed.');
        $loan->update(['status' => 'rejected']);
        return back()->with('success','Loan rejected.');
    }

    public function markPaid(Request $request, LoanApplication $loan, LoanRepayment $repayment)
    {
        abort_unless($loan->id === $repayment->loan_application_id, 404);
        $repayment->update(['status'=>'paid','paid_at'=>now()]);
        return back()->with('success','Repayment marked as paid.');
    }
}
