<?php

namespace App\Filament\Technician\Widgets;

use Filament\Widgets\StatsOverviewWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;
use Illuminate\Support\Facades\Auth;

class TechnicianStatsOverview extends StatsOverviewWidget
{
    protected static ?int $sort = 1;

    protected function getStats(): array
    {
        $technician = Auth::guard('technician')->user();

        $totalOrders = $technician->orders()->count();
        $pendingOrders = $technician->orders()->where('status', 'pending')->count();
        $inProgressOrders = $technician->orders()->where('status', 'in_progress')->count();
        $completedOrders = $technician->orders()->where('status', 'completed')->count();
        $cancelledOrders = $technician->orders()->where('status', 'cancelled')->count();

        $avgRating = $technician->orders()
            ->whereHas('rating')
            ->with('rating')
            ->get()
            ->pluck('rating.rating')
            ->avg();

        // حساب إجمالي المستحقات من الطلبات المكتملة
        $totalCommission = $technician->orders()
            ->where('status', 'completed')
            ->sum('technician_commission');

        return [
            Stat::make('إجمالي الطلبات', $totalOrders)
                ->description('جميع الطلبات')
                ->descriptionIcon('heroicon-m-clipboard-document-list')
                ->color('primary')
                ->chart([2, 3, 4, 3, 5, 4, 6]),

            Stat::make('طلبات قيد الانتظار', $pendingOrders)
                ->description('تحتاج تأكيد')
                ->descriptionIcon('heroicon-m-clock')
                ->color('warning')
                ->chart([1, 2, 1, 3, 2, 1, 2]),

            Stat::make('طلبات قيد التنفيذ', $inProgressOrders)
                ->description('جاري العمل عليها')
                ->descriptionIcon('heroicon-m-arrow-path')
                ->color('info')
                ->chart([1, 1, 2, 1, 2, 1, 1]),

            Stat::make('طلبات مكتملة', $completedOrders)
                ->description('تم إنجازها')
                ->descriptionIcon('heroicon-m-check-circle')
                ->color('success')
                ->chart([1, 2, 3, 2, 4, 3, 5]),

            Stat::make('إجمالي المستحقات', number_format($totalCommission, 2) . ' ر.س')
                ->description('من الطلبات المكتملة')
                ->descriptionIcon('heroicon-m-currency-dollar')
                ->color('success')
                ->chart([100, 150, 200, 180, 250, 220, 300]),

            Stat::make('متوسط التقييم', $avgRating ? number_format($avgRating, 1) . ' / 5' : 'لا يوجد')
                ->description('تقييم العملاء')
                ->descriptionIcon('heroicon-m-star')
                ->color('warning')
                ->chart([3, 4, 4, 5, 4, 5, 4]),
        ];
    }
}

