<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Models\Agent;
use App\Models\Customer;
use App\Models\Loan;
use App\Models\SubscriptionPlan;
use App\Models\SupportTicket;
use App\Models\Tenant;
use App\Models\TenantPayment;
use Illuminate\View\View;

class DashboardController extends Controller
{
    public function __invoke(): View
    {
        return view('super.dashboard', [
            'tenantsTotal' => Tenant::count(),
            'activeTenants' => Tenant::activeAccess()->count(),
            'trialTenants' => Tenant::onTrial()->count(),
            'newTenants' => Tenant::newTenants()->count(),
            'expiredTenants' => Tenant::expired()->count(),
            'activeAgents' => Agent::where('status', Agent::STATUS_ACTIVE)->count(),
            'pendingAgents' => Agent::where('status', Agent::STATUS_PENDING)->count(),
            'activePlans' => SubscriptionPlan::where('is_active', true)->count(),
            'monthlyRevenue' => TenantPayment::withoutGlobalScopes()->where('status', 'approved')->whereMonth('approved_at', now()->month)->sum('amount'),
            'totalRevenue' => TenantPayment::withoutGlobalScopes()->where('status', 'approved')->sum('amount'),
            'customersTotal' => Customer::withoutGlobalScopes()->count(),
            'activeLoans' => Loan::withoutGlobalScopes()->whereIn('status', ['active', 'disbursed'])->count(),
            'openTickets' => SupportTicket::withoutGlobalScopes()->whereIn('status', ['open', 'in_progress'])->count(),
            'newTenantsList' => Tenant::latest()->limit(8)->get(),
            'pendingPayments' => TenantPayment::withoutGlobalScopes()->with(['tenant', 'plan'])->where('status', 'pending')->latest()->limit(8)->get(),
        ]);
    }
}
