<?php

namespace App\Filament\Widgets;

use App\Models\Order;
use Filament\Widgets\StatsOverviewWidget as BaseWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;

class ProfitMarginWidget extends BaseWidget
{
    protected static ?int $sort = 2;

    protected function getStats(): array
    {
        $totalProfit = 0.00;
        $totalRevenue = 0.00;

        $paidOrders = Order::where('payment_status', 'paid')
            ->with('items.product')
            ->get();

        foreach ($paidOrders as $order) {
            $totalRevenue += (float) $order->subtotal;

            foreach ($order->items as $item) {
                $price = (float) $item->price;
                $quantity = (int) $item->quantity;
                $cost = (float) ($item->product->cost_price ?? 0.00);

                $totalProfit += ($price - $cost) * $quantity;
            }
        }

        $totalRefunds = (float) \App\Models\ReturnRequest::where('status', 'completed')->sum('refund_amount');
        $totalProfit -= $totalRefunds;
        $totalRevenue -= $totalRefunds;

        $netMargin = $totalRevenue > 0.00 ? ($totalProfit / $totalRevenue) * 100 : 0.00;

        $averageOrderValue = Order::where('payment_status', 'paid')
            ->avg('grand_total') ?? 0.00;

        return [
            Stat::make('Net Profit', '৳' . number_format($totalProfit, 2))
                ->description('Accumulated profit from paid orders')
                ->descriptionIcon('heroicon-m-currency-bangladeshi')
                ->color('success'),
            Stat::make('Net Profit Margin', number_format($netMargin, 1) . '%')
                ->description('Profit margin relative to product sales')
                ->descriptionIcon('heroicon-m-percent-badge')
                ->color('info'),
            Stat::make('Average Order Value (AOV)', '৳' . number_format($averageOrderValue, 2))
                ->description('Average checkout size of paid orders')
                ->descriptionIcon('heroicon-m-shopping-cart')
                ->color('warning'),
        ];
    }
}
