<?php

declare(strict_types=1);

namespace App\Filament\Admin\Widgets;

use App\Models\Domain;
use App\Models\SslCertificate;
use Filament\Widgets\StatsOverviewWidget as BaseWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;

class SslStatsOverview extends BaseWidget
{
    protected ?string $pollingInterval = '30s';

    protected function getStats(): array
    {
        $totalDomains = Domain::count();
        $domainsWithSsl = SslCertificate::where('status', 'active')->count();
        $expiringSoon = SslCertificate::where('status', 'active')
            ->where('expires_at', '<=', now()->addDays(30))
            ->where('expires_at', '>', now())
            ->count();
        $expired = SslCertificate::where('status', 'expired')
            ->orWhere(function ($q) {
                $q->where('expires_at', '<', now());
            })
            ->count();
        $failed = SslCertificate::where('status', 'failed')->count();
        $withoutSsl = $totalDomains - $domainsWithSsl;

        return [
            Stat::make(__('Total Domains'), (string) $totalDomains)
                ->description(__('All registered domains'))
                ->descriptionIcon('heroicon-m-globe-alt')
                ->color('gray'),

            Stat::make(__('With SSL'), (string) $domainsWithSsl)
                ->description(__('Active certificates'))
                ->descriptionIcon('heroicon-m-shield-check')
                ->color('success'),

            Stat::make(__('Without SSL'), (string) $withoutSsl)
                ->description(__('No certificate'))
                ->descriptionIcon('heroicon-m-shield-exclamation')
                ->color('gray'),

            Stat::make(__('Expiring Soon'), (string) $expiringSoon)
                ->description(__('Within 30 days'))
                ->descriptionIcon('heroicon-m-clock')
                ->color($expiringSoon > 0 ? 'warning' : 'success'),

            Stat::make(__('Expired'), (string) $expired)
                ->description(__('Need renewal'))
                ->descriptionIcon('heroicon-m-x-circle')
                ->color($expired > 0 ? 'danger' : 'success'),

            Stat::make(__('Failed'), (string) $failed)
                ->description(__('Issuance failed'))
                ->descriptionIcon('heroicon-m-exclamation-triangle')
                ->color($failed > 0 ? 'danger' : 'success'),
        ];
    }
}
