<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Account;
use App\Models\ChartOfAccount;
use App\Models\Loan;
use App\Models\TreasuryPosition;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;

class ReportController extends Controller
{
    public function portfolio(): View
    {
        $portfolioByStatus = Loan::query()
            ->select('status', DB::raw('COUNT(*) as count'), DB::raw('SUM(principal) as total_principal'), DB::raw('SUM(outstanding_principal) as outstanding'))
            ->groupBy('status')
            ->orderBy('status')
            ->get();

        $portfolioByProduct = Loan::query()
            ->join('loan_products', 'loans.product_id', '=', 'loan_products.id')
            ->select(
                'loan_products.name as product_name',
                DB::raw('COUNT(*) as count'),
                DB::raw('SUM(loans.outstanding_principal) as outstanding'),
            )
            ->groupBy('loan_products.id', 'loan_products.name')
            ->orderByDesc('outstanding')
            ->get();

        $totals = [
            'loan_count' => Loan::query()->count(),
            'total_outstanding' => Loan::query()->sum('outstanding_principal'),
            'active_count' => Loan::query()->whereIn('status', ['active', 'in_arrears'])->count(),
        ];

        return view('admin.reports.portfolio', compact('portfolioByStatus', 'portfolioByProduct', 'totals'));
    }

    public function liquidity(): View
    {
        $cashAccounts = ChartOfAccount::query()
            ->where('code', 'like', '1%')
            ->where('is_postable', true)
            ->orderBy('code')
            ->get();

        $deposits = Account::query()
            ->whereIn('account_type', ['savings', 'current'])
            ->where('status', 'active')
            ->sum('balance');

        $treasuryPositions = TreasuryPosition::query()
            ->where('status', 'open')
            ->select(DB::raw('SUM(cost_amount) as total_cost'), DB::raw('SUM(market_value) as total_market_value'))
            ->first();

        $summary = [
            'total_deposits' => $deposits,
            'treasury_cost' => $treasuryPositions->total_cost ?? 0,
            'treasury_market_value' => $treasuryPositions->total_market_value ?? 0,
            'cash_gl_balance' => $cashAccounts->sum('balance'),
        ];

        return view('admin.reports.liquidity', compact('cashAccounts', 'summary'));
    }

    public function incomeSummary(): View
    {
        $interestIncome = ChartOfAccount::query()
            ->where('account_class', 'income')
            ->where('code', 'like', '4%')
            ->orderBy('code')
            ->get();

        $expenses = ChartOfAccount::query()
            ->where('account_class', 'expense')
            ->orderBy('code')
            ->get();

        $summary = [
            'total_income' => $interestIncome->sum('balance'),
            'total_expenses' => $expenses->sum('balance'),
            'net_income' => $interestIncome->sum('balance') - $expenses->sum('balance'),
        ];

        return view('admin.reports.income', compact('interestIncome', 'expenses', 'summary'));
    }
}
