<?php

namespace App\Filament\Widgets;

use Filament\Widgets\StatsOverviewWidget as BaseWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;
use App\Models\Transaction;
use App\Models\Gateway;
use App\Models\SmsLog;
use App\Models\Setting;
use Carbon\Carbon;

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

    protected function getStats(): array
    {
        $totalVolume = Transaction::whereIn('status', ['SUCCESS', 'Complete', 'COMPLETED'])->sum('amount');
        $successCount = Transaction::whereIn('status', ['SUCCESS', 'Complete', 'COMPLETED'])->count();
        $totalCount = Transaction::count();
        $pendingCount = Transaction::whereIn('status', ['PENDING', 'Pending'])->count();
        $activeGateways = Gateway::where('is_active', true)->count();
        $unmatchedSms = SmsLog::where('status', 'UNMATCHED')->count();
        
        $successRate = $totalCount > 0 ? round(($successCount / $totalCount) * 100) : 0;
        $currencySymbol = setting('currency_symbol', '৳');

        // Past 7 days volume trend for sparkline chart
        $sparkline = [];
        for ($i = 6; $i >= 0; $i--) {
            $dayStart = now()->subDays($i)->startOfDay();
            $dayEnd = now()->subDays($i)->endOfDay();
            $sparkline[] = (float) Transaction::whereBetween('created_at', [$dayStart, $dayEnd])
                ->whereIn('status', ['SUCCESS', 'Complete', 'COMPLETED'])
                ->sum('amount');
        }

        return [
            Stat::make('Total Revenue', $currencySymbol . ' ' . number_format($totalVolume, 2))
                ->description($successCount . ' successful transactions (' . $successRate . '% rate)')
                ->descriptionIcon('heroicon-m-arrow-trending-up')
                ->chart($sparkline)
                ->color('success'),

            Stat::make('Pending Verification', $pendingCount)
                ->description($unmatchedSms . ' unmatched SMS logs in queue')
                ->descriptionIcon('heroicon-m-clock')
                ->color('warning'),

            Stat::make('Active Gateways', $activeGateways . ' Online')
                ->description('bKash, Nagad, Rocket & Crypto')
                ->descriptionIcon('heroicon-m-bolt')
                ->color('primary'),

            Stat::make('License Status', function () {
                $status = Setting::where('key', 'license_status')->value('value');
                return $status ?: 'ACTIVE';
            })
                ->description(function () {
                    $expiresAt = Setting::where('key', 'license_expires_at')->value('value');
                    return $expiresAt ? "Expires: " . date('M d, Y', strtotime($expiresAt)) : 'Lifetime Verified';
                })
                ->descriptionIcon('heroicon-m-shield-check')
                ->color('success'),
        ];
    }
}
