<?php

namespace App\Filament\Central\Widgets;

use App\Models\Central\Tenant;
use Filament\Widgets\StatsOverviewWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;
use Illuminate\Support\Facades\DB;

/**
 * Headline figures for the master-control dashboard: the tenant population by
 * status and the total staff count across every tenant.
 *
 * Central data only — Tenant never tenant-scopes itself, and the user count
 * goes through DB::table('users') exactly like TenantResource::userCountFor()
 * (the landlord panel has no tenant bound, so a scoped Eloquent query would
 * have nothing to filter against anyway).
 */
class CentralTenantsOverview extends StatsOverviewWidget
{
    protected static ?int $sort = 1;

    protected function getStats(): array
    {
        // Live tenants only — test instances are counted by test instances,
        // not by this dashboard's tenant population stats.
        $total = (int) Tenant::query()->live()->count();
        $active = (int) Tenant::query()->live()->where('status', Tenant::STATUS_ACTIVE)->count();
        $trial = (int) Tenant::query()->live()->where('status', Tenant::STATUS_TRIAL)->count();
        $suspended = (int) Tenant::query()->live()->where('status', Tenant::STATUS_SUSPENDED)->count();

        $totalUsers = (int) DB::table('users')
            ->whereNull('deleted_at')
            ->count();

        return [
            Stat::make('Total tenants', (string) $total)
                ->description($active.' active · '.$trial.' trial')
                ->color('primary'),
            Stat::make('Active tenants', (string) $active)
                ->description('Currently serving requests')
                ->color('success'),
            Stat::make('Suspended tenants', (string) $suspended)
                ->description($suspended > 0 ? 'Awaiting review or action' : 'All clear')
                ->color($suspended > 0 ? 'danger' : 'gray'),
            Stat::make('Total users', (string) $totalUsers)
                ->description('Across all tenants')
                ->color('info'),
        ];
    }
}
