<?php

namespace App\Filament\Widgets;

use App\Models\Order;
use App\Models\PurchaseOrder;
use App\Models\User;
use Filament\Widgets\StatsOverviewWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;
use Illuminate\Support\Facades\DB;

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

    protected function getStats(): array
    {
        $activeStatuses = [
            Order::STATUS_DELIVERED,
            Order::STATUS_SHIPPING,
            Order::STATUS_PROCESSING,
        ];

        $orderStats = Order::query()
            ->selectRaw("
                SUM(CASE WHEN status IN ('delivered','shipping','processing') THEN total ELSE 0 END) as total_revenue,
                SUM(CASE WHEN status IN ('delivered','shipping','processing') THEN total_profit ELSE 0 END) as total_profit,
                SUM(CASE WHEN DATE(created_at) = CURDATE() THEN 1 ELSE 0 END) as today_orders,
                SUM(CASE WHEN status = 'delivered' THEN points_earned ELSE 0 END) as total_points
            ")
            ->first();

        $pendingSupplier = PurchaseOrder::where('status', 'pending')->count();
        $totalMerchants = User::where('is_admin', false)->where('is_active', true)->count();

        return [
            Stat::make('إجمالي الإيرادات', number_format($orderStats->total_revenue ?? 0, 2) . ' ج.م')
                ->description('من الطلبات النشطة')
                ->color('success'),

            Stat::make('إجمالي الأرباح', number_format($orderStats->total_profit ?? 0, 2) . ' ج.م')
                ->description('صافي الربح')
                ->color('info'),

            Stat::make('طلبات اليوم', $orderStats->today_orders ?? 0)
                ->description('طلبات جديدة')
                ->color('warning'),

            Stat::make('أوامر شراء معلقة', $pendingSupplier)
                ->description('بانتظار التأكيد')
                ->color($pendingSupplier > 0 ? 'danger' : 'success'),

            Stat::make('التجار النشطون', $totalMerchants)
                ->description('تجار مسجلون')
                ->color('primary'),

            Stat::make('نقاط صادرة', number_format($orderStats->total_points ?? 0))
                ->description('من طلبات مسلمة')
                ->color('warning'),
        ];
    }
}
