<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Loan;
use App\Models\LoanInstallment;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AdminLoanDashboardController extends Controller
{
    public function index(Request $request)
    {
        // 1) Users who took loans (with counts)
        $users = User::whereHas('loans')
            ->withCount([
                'loans as total_loans',
                'loans as completed_loans' => fn($q)=>$q->where('status','completed'),
                'loans as running_loans'   => fn($q)=>$q->where('status','running'),
            ])
            ->orderBy('id','desc')
            ->paginate(15);

        // 2) (Implicit in users table) — completed_loans per user

        // 3) Installments needing approval (submitted)
        $pendingInstallments = LoanInstallment::with(['loan.user'])
            ->where('status','submitted')
            ->orderBy('created_at','desc')
            ->paginate(15);

        return view('admin.loans.dashboard', compact('users','pendingInstallments'));
    }

    public function approve(LoanInstallment $installment)
    {
        // mark installment as paid
        $installment->update([
            'status'  => 'paid',
            'paid_at' => $installment->paid_at ?? now(),
        ]);

        // if all installments are paid → mark loan completed
        $loan = $installment->loan;
        if ($loan && $loan->installments()->where('status','!=','paid')->count() === 0) {
            $loan->update([
                'status'       => 'completed',
                'completed_at' => now(),
            ]);
        }

        return back()->with('success','Installment approved & marked as PAID.');
    }
}
