<?php

namespace App\Filament\AssociationAdmin\Widgets;

use App\Models\Order;
use App\Models\ProjectCharter;
use BezhanSalleh\FilamentShield\Traits\HasWidgetShield;
use Filament\Widgets\StatsOverviewWidget as BaseWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Number;

class AssociationStatsOverview extends BaseWidget
{
    use HasWidgetShield;

    public static ?int $sort = 1;

    protected function getHeading(): string
    {
        return __('association-admin-dashboard.dashboard').' - '.'إحصائيات الجهة';
    }

    protected function getStats(): array
    {
        $user = Auth::user();
        $association = $user?->association;

        if (! $association) {
            return [];
        }

        // Build base query for orders
        $ordersQuery = Order::where('association_id', $association->id);

        // Get orders for this association
        $totalOrders = (clone $ordersQuery)->count();
        $approvedOrders = (clone $ordersQuery)->where('status', Order::STATUS_ACCEPTED)->count();

        // Get project charters for this association through approved orders
        $projectsQuery = ProjectCharter::whereHas('order', function ($query) use ($association) {
            $query->where('association_id', $association->id)
                ->where('status', Order::STATUS_ACCEPTED);
        });

        $approvedProjectsValue = $projectsQuery->sum('estimated_cost');

        return [
            Stat::make('عدد الطلبات المقدمة', Number::format($totalOrders))
                ->description('إجمالي الطلبات المقدمة من الجهة')
                ->descriptionIcon('heroicon-m-document-text')
                ->color('primary'),

            Stat::make('عدد الطلبات المعتمدة', Number::format($approvedOrders))
                ->description('الطلبات التي تم اعتمادها')
                ->descriptionIcon('heroicon-m-check-circle')
                ->color('success'),

            Stat::make('قيمة المشاريع المعتمدة', Number::format($approvedProjectsValue).' ريال')
                ->description('إجمالي قيمة المشاريع المعتمدة')
                ->descriptionIcon('heroicon-m-banknotes')
                ->color('warning'),
        ];
    }

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