<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Loan;
use App\Models\LoanInstallment;
use App\Models\LoanDeposit;
use App\Models\WithdrawRequest;
use Carbon\Carbon;

class AdminDashboardController extends Controller
{
    public function admin_dashboard()
    {
        // ====== CARD METRICS (8 ta card) ======

        // Users
        $totalUsers   = User::count();
        $activeUsers  = User::where('status', 'active')->count();

        // Loans
        $totalLoans     = Loan::count();
        $runningLoans   = Loan::where('status', 'running')->count();
        $pendingLoans   = Loan::whereIn('status', [
            'pending_deposit',
            'pending_approval',
            'nid_uploaded',
            'summary_confirmed',
            'draft',
        ])->count();
        $completedLoans = Loan::where('status', 'completed')->count();
        $rejectedLoans  = Loan::where('status', 'rejected')->count();

        // Disbursed amount = approved / running / completed loans
        $totalDisbursed = Loan::whereIn('status', ['running', 'completed'])
            ->sum('amount');

        // EMI (installments)
        $overdueEmi = LoanInstallment::where('status', 'late')->count();
        $paidEmi    = LoanInstallment::where('status', 'paid')->count();

        // Withdraw stats (extra)
        $pendingWithdraw = WithdrawRequest::where('status', 'pending')->count();
        $totalWithdrawn  = WithdrawRequest::where('status', 'approved')->sum('amount');

        // ====== CHART DATA (last 6 months) ======
        $months    = collect(range(5, 0, -1))->map(
            fn ($i) => Carbon::now()->subMonths($i)->startOfMonth()
        );

        $chartMonths        = [];
        $chartLoansCreated  = [];
        $chartLoansApproved = [];
        $chartDepositAmount = [];
        $chartWithdrawAmount = [];

        foreach ($months as $month) {
            $year  = $month->year;
            $m     = $month->month;
            $label = $month->format('M Y');

            $chartMonths[] = $label;

            // total loans created in this month
            $chartLoansCreated[] = Loan::whereYear('created_at', $year)
                ->whereMonth('created_at', $m)
                ->count();

            // loans approved this month (approved_at)
            $chartLoansApproved[] = Loan::whereNotNull('approved_at')
                ->whereYear('approved_at', $year)
                ->whereMonth('approved_at', $m)
                ->count();

            // approved deposits (loan_deposits)
            $chartDepositAmount[] = LoanDeposit::where('status', 'approved')
                ->whereYear('created_at', $year)
                ->whereMonth('created_at', $m)
                ->sum('amount');

            // approved withdraws
            $chartWithdrawAmount[] = WithdrawRequest::where('status', 'approved')
                ->whereYear('created_at', $year)
                ->whereMonth('created_at', $m)
                ->sum('amount');
        }

        return view('backend.dashboard', [
            // cards
            'totalUsers'        => $totalUsers,
            'activeUsers'       => $activeUsers,
            'totalLoans'        => $totalLoans,
            'runningLoans'      => $runningLoans,
            'pendingLoans'      => $pendingLoans,
            'completedLoans'    => $completedLoans,
            'rejectedLoans'     => $rejectedLoans,
            'totalDisbursed'    => $totalDisbursed,
            'overdueEmi'        => $overdueEmi,
            'paidEmi'           => $paidEmi,
            'pendingWithdraw'   => $pendingWithdraw,
            'totalWithdrawn'    => $totalWithdrawn,

            // charts
            'chartMonths'        => $chartMonths,
            'chartLoansCreated'  => $chartLoansCreated,
            'chartLoansApproved' => $chartLoansApproved,
            'chartDepositAmount' => $chartDepositAmount,
            'chartWithdrawAmount'=> $chartWithdrawAmount,
        ]);
    }
}
