<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Models\AppNotification;
use App\Models\Customer;
use App\Models\Loan;
use App\Models\LoanPayment;
use App\Models\LoanRepaymentSchedule;
use App\Models\SavingsAccount;
use App\Models\SavingsTransaction;
use Illuminate\View\View;

class DashboardController extends Controller
{
    public function __invoke(): View
    {
        $user = auth()->user();

        return view('tenant.dashboard', [
            'totalCustomers' => Customer::visibleTo($user)->count(),
            'newCustomersThisMonth' => Customer::visibleTo($user)->whereMonth('created_at', now()->month)->whereYear('created_at', now()->year)->count(),
            'savingsAccountCount' => SavingsAccount::whereHas('customer', fn ($query) => $query->visibleTo($user))->count(),
            'totalSavings' => SavingsAccount::whereHas('customer', fn ($query) => $query->visibleTo($user))->sum('balance'),
            'dueLoanCount' => Loan::whereHas('customer', fn ($query) => $query->visibleTo($user))
                ->whereIn('status', ['active', 'disbursed'])
                ->whereHas('schedules', fn ($query) => $query->whereDate('due_date', '<=', today())->whereIn('status', ['pending', 'partial', 'overdue']))
                ->count(),
            'loanPortfolio' => Loan::whereHas('customer', fn ($query) => $query->visibleTo($user))->whereIn('status', ['active', 'disbursed'])->sum('balance'),
            'activeLoanCount' => Loan::whereHas('customer', fn ($query) => $query->visibleTo($user))->whereIn('status', ['active', 'disbursed'])->count(),
            'totalDisbursedAmount' => Loan::whereHas('customer', fn ($query) => $query->visibleTo($user))->where('amount_disbursed', '>', 0)->sum('amount_disbursed'),
            'disbursedLoanCount' => Loan::whereHas('customer', fn ($query) => $query->visibleTo($user))->where('amount_disbursed', '>', 0)->count(),
            'totalRepaidAmount' => LoanPayment::posted()->whereHas('customer', fn ($query) => $query->visibleTo($user))->sum('amount'),
            'repaymentCount' => LoanPayment::posted()->whereHas('customer', fn ($query) => $query->visibleTo($user))->count(),
            'todayDisbursedAmount' => Loan::whereHas('customer', fn ($query) => $query->visibleTo($user))->whereDate('disbursed_at', today())->sum('amount_disbursed'),
            'todayDisbursedLoanCount' => Loan::whereHas('customer', fn ($query) => $query->visibleTo($user))->whereDate('disbursed_at', today())->count(),
            'todayRepaidAmount' => LoanPayment::posted()->whereHas('customer', fn ($query) => $query->visibleTo($user))->whereDate('paid_at', today())->sum('amount'),
            'todayRepaymentCount' => LoanPayment::posted()->whereHas('customer', fn ($query) => $query->visibleTo($user))->whereDate('paid_at', today())->count(),
            'monthDisbursedAmount' => Loan::whereHas('customer', fn ($query) => $query->visibleTo($user))->whereBetween('disbursed_at', [now()->startOfMonth(), now()->endOfMonth()])->sum('amount_disbursed'),
            'monthDisbursedLoanCount' => Loan::whereHas('customer', fn ($query) => $query->visibleTo($user))->whereBetween('disbursed_at', [now()->startOfMonth(), now()->endOfMonth()])->count(),
            'monthRepaidAmount' => LoanPayment::posted()->whereHas('customer', fn ($query) => $query->visibleTo($user))->whereBetween('paid_at', [now()->startOfMonth(), now()->endOfMonth()])->sum('amount'),
            'monthRepaymentCount' => LoanPayment::posted()->whereHas('customer', fn ($query) => $query->visibleTo($user))->whereBetween('paid_at', [now()->startOfMonth(), now()->endOfMonth()])->count(),
            'todayDeposits' => SavingsTransaction::whereHas('customer', fn ($query) => $query->visibleTo($user))->where('type', 'deposit')->where('status', 'posted')->whereDate('transacted_at', today())->sum('amount'),
            'todayWithdrawals' => SavingsTransaction::whereHas('customer', fn ($query) => $query->visibleTo($user))->where('type', 'withdrawal')->where('status', 'posted')->whereDate('transacted_at', today())->sum('amount'),
            'monthDeposits' => SavingsTransaction::whereHas('customer', fn ($query) => $query->visibleTo($user))->where('type', 'deposit')->where('status', 'posted')->whereBetween('transacted_at', [now()->startOfMonth(), now()->endOfMonth()])->sum('amount'),
            'monthWithdrawals' => SavingsTransaction::whereHas('customer', fn ($query) => $query->visibleTo($user))->where('type', 'withdrawal')->where('status', 'posted')->whereBetween('transacted_at', [now()->startOfMonth(), now()->endOfMonth()])->sum('amount'),
            'dueToday' => LoanRepaymentSchedule::whereHas('loan.customer', fn ($query) => $query->visibleTo($user))->whereDate('due_date', today())->whereIn('status', ['pending', 'partial'])->sum('total_due'),
            'overdueCount' => LoanRepaymentSchedule::whereHas('loan.customer', fn ($query) => $query->visibleTo($user))->whereDate('due_date', '<', today())->whereIn('status', ['pending', 'partial', 'overdue'])->count(),
            'dueSchedules' => LoanRepaymentSchedule::query()
                ->with(['loan.customer'])
                ->whereHas('loan.customer', fn ($query) => $query->visibleTo($user))
                ->whereDate('due_date', '<=', today())
                ->whereIn('status', ['pending', 'partial', 'overdue'])
                ->orderBy('due_date')
                ->limit(6)
                ->get(),
            'recentCustomers' => Customer::visibleTo($user)->latest()->limit(6)->get(),
            'recentLoans' => Loan::with('customer')->whereHas('customer', fn ($query) => $query->visibleTo($user))->latest()->limit(6)->get(),
            'notifications' => AppNotification::whereNull('user_id')->latest()->limit(6)->get(),
        ]);
    }
}
