<?php

namespace App\Filament\Resources\UserResource\Widgets;

use App\Models\User;
use Filament\Widgets\StatsOverviewWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;
use Illuminate\Support\Facades\Auth;

/**
 * Headline figures for the Users list — totals are TenantScope-limited
 * automatically. Mirrors the source user-management dashboard summary
 * (docs/migration-plan.md Phase 12).
 */
class UserStatsOverview extends StatsOverviewWidget
{
    protected function getStats(): array
    {
        $total = (int) User::query()->count();
        $active = (int) User::query()->where('status', User::STATUS_ACTIVE)->count();
        $suspended = (int) User::query()->where('status', User::STATUS_SUSPENDED)->count();
        $locked = (int) User::query()->where('locked_until', '>', now())->count();
        $twoFactor = (int) User::query()
            ->where(fn ($q) => $q->where('two_factor_email_enabled', true)->orWhereNotNull('two_factor_confirmed_at'))
            ->count();
        $mustChange = (int) User::query()->where('must_change_password', true)->count();

        return [
            Stat::make('Total users', (string) $total)
                ->description($active.' active'),
            Stat::make('Active', (string) $active)
                ->color('success')
                ->description(($total > 0 ? round($active / $total * 100) : 0).'% of users'),
            Stat::make('Suspended', (string) $suspended)
                ->color($suspended > 0 ? 'warning' : 'gray'),
            Stat::make('Locked out', (string) $locked)
                ->color($locked > 0 ? 'danger' : 'gray'),
            Stat::make('2FA enabled', (string) $twoFactor)
                ->description($mustChange.' must change password')
                ->color('gray'),
        ];
    }

    public static function canView(): bool
    {
        return Auth::user()?->hasPermissionTo('user_management_users.access') ?? false;
    }
}
