<?php

namespace App\Filament\Widgets;

use App\Models\Association;
use App\Models\Order;
use BezhanSalleh\FilamentShield\Traits\HasWidgetShield;
use Filament\Widgets\Concerns\InteractsWithPageFilters;
use Filament\Widgets\StatsOverviewWidget as BaseWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;
use Illuminate\Support\Number;

class AssociationsDashboardStatsOverview extends BaseWidget
{
    use HasWidgetShield, InteractsWithPageFilters;

    public static ?int $sort = 1;

    public function getHeading(): string
    {
        return __('pages.orders_dashboard').' - '.__('widgets.number_of_associations');
    }

    protected function getStats(): array
    {
        // Get filter value
        $selectedYear = $this->filters['year'] ?? null;

        // Build query for accepted orders with year filter
        $familiesQuery = Order::where('status', Order::STATUS_ACCEPTED)->filterByTypePermissions();

        if ($selectedYear) {
            $familiesQuery->whereYear('created_at', $selectedYear);
        }

        $totalFamilies = $familiesQuery->sum('number_of_families');

        return [
            Stat::make(__('widgets.number_of_associations'), Number::format(Association::count()))
                ->description(__('widgets.number_of_associations_description'))
                ->descriptionIcon('heroicon-m-building-office')
                ->color('primary'),

            Stat::make(__('widgets.number_of_verified_associations'), Number::format(Association::where('is_verified', true)->count()))
                ->description(__('widgets.number_of_verified_associations_description'))
                ->descriptionIcon('heroicon-m-check-badge')
                ->color('success'),

            Stat::make(__('widgets.number_of_families'), Number::format($totalFamilies))
                ->description(__('widgets.number_of_families_description'))
                ->descriptionIcon('heroicon-m-user-group')
                ->color('info'),
        ];
    }

    public function getColumns(): int
    {
        return 3;
    }
}
