<?php

namespace App\Filament\Widgets;

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

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

    protected function getStats(): array
    {
        $grossSales = Order::whereNotIn('status', ['cancelled'])
            ->where('payment_status', '!=', 'failed')
            ->sum('subtotal');

        $totalDiscounts = Order::whereNotIn('status', ['cancelled'])
            ->where('payment_status', '!=', 'failed')
            ->sum('discount');

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

        $totalRefunds = Order::where('payment_status', 'refunded')
            ->sum('grand_total') + $returnRequestRefunds;

        $netSales = $grossSales - $totalDiscounts - $totalRefunds;

        $totalOrders = Order::count();
        $pendingOrders = Order::where('status', 'pending')->count();

        // 7-day trend calculations for sparklines
        $salesTrend = [];
        $netSalesTrend = [];
        $ordersTrend = [];
        $pendingTrend = [];

        for ($i = 6; $i >= 0; $i--) {
            $dateStart = now()->subDays($i)->startOfDay();
            $dateEnd = now()->subDays($i)->endOfDay();

            // Daily gross sales
            $dailyGross = Order::whereNotIn('status', ['cancelled'])
                ->where('payment_status', '!=', 'failed')
                ->whereBetween('created_at', [$dateStart, $dateEnd])
                ->sum('subtotal') ?: 0.0;
            $salesTrend[] = (float) $dailyGross;

            // Daily discounts & refunds
            $dailyDiscounts = Order::whereNotIn('status', ['cancelled'])
                ->where('payment_status', '!=', 'failed')
                ->whereBetween('created_at', [$dateStart, $dateEnd])
                ->sum('discount') ?: 0.0;

            $dailyRefundRequests = (float) \App\Models\ReturnRequest::where('status', 'completed')
                ->whereBetween('created_at', [$dateStart, $dateEnd])
                ->sum('refund_amount') ?: 0.0;

            $dailyOrderRefunds = Order::where('payment_status', 'refunded')
                ->whereBetween('created_at', [$dateStart, $dateEnd])
                ->sum('grand_total') ?: 0.0;

            $dailyRefunds = $dailyOrderRefunds + $dailyRefundRequests;
            $netSalesTrend[] = (float) ($dailyGross - $dailyDiscounts - $dailyRefunds);

            // Daily total orders
            $ordersTrend[] = Order::whereBetween('created_at', [$dateStart, $dateEnd])->count();

            // Daily pending orders
            $pendingTrend[] = Order::where('status', 'pending')
                ->whereBetween('created_at', [$dateStart, $dateEnd])
                ->count();
        }

        return [
            Stat::make('Gross Sales', '৳' . number_format($grossSales, 2))
                ->description('Total order value before discounts/refunds')
                ->descriptionIcon('heroicon-m-banknotes')
                ->chart($salesTrend)
                ->color('primary'),
            Stat::make('Net Sales', '৳' . number_format($netSales, 2))
                ->description('Gross sales minus discounts and refunds')
                ->descriptionIcon('heroicon-m-currency-bangladeshi')
                ->chart($netSalesTrend)
                ->color('success'),
            Stat::make('Total Orders', $totalOrders)
                ->description('All time storefront orders')
                ->descriptionIcon('heroicon-m-shopping-bag')
                ->chart($ordersTrend)
                ->color('info'),
            Stat::make('Pending Orders', $pendingOrders)
                ->description('Awaiting fulfillment')
                ->descriptionIcon('heroicon-m-clock')
                ->chart($pendingTrend)
                ->color('warning'),
        ];
    }
}
