<?php

namespace App\Http\Controllers\Portal;

use App\Http\Controllers\Controller;
use App\Models\Account;
use App\Models\AccountTransaction;
use App\Models\Customer;
use App\Models\Investment;
use App\Models\Loan;
use Illuminate\View\View;

class DashboardController extends Controller
{
    public function index(): View
    {
        $customer = $this->resolveCustomer();

        $accounts = Account::query()
            ->where('customer_id', $customer->id)
            ->where('status', 'active')
            ->get();

        $loans = Loan::query()
            ->where('customer_id', $customer->id)
            ->with(['loanProduct', 'schedules', 'repayments'])
            ->latest()
            ->get();

        $investments = Investment::query()
            ->where('customer_id', $customer->id)
            ->with('investmentProduct')
            ->latest()
            ->get();

        $recentTransactions = AccountTransaction::query()
            ->whereIn('account_id', $accounts->pluck('id'))
            ->with('account')
            ->latest()
            ->limit(10)
            ->get();

        $activeLoans = $loans->whereIn('status', ['active', 'in_arrears', 'disbursed']);

        $summary = [
            'total_balance' => $accounts->sum('balance'),
            'active_loans' => $activeLoans->count(),
            'total_outstanding' => $loans->sum('outstanding_principal'),
            'interest_accrued' => $activeLoans->sum(fn (Loan $l) => $l->interestSummary()['accrued_estimate']),
            'total_investments' => $investments->where('status', 'active')->sum('principal'),
        ];

        return view('portal.dashboard', compact(
            'customer',
            'accounts',
            'loans',
            'investments',
            'recentTransactions',
            'summary',
            'activeLoans',
        ));
    }

    protected function resolveCustomer(): Customer
    {
        return Customer::query()->findOrFail(session('portal_customer_id'));
    }
}
