<?php

namespace App\Filament\Widgets;

use App\Models\Lead;
use App\Models\Order;
use App\Models\User;
use App\Models\SiteActivity;
use Filament\Widgets\StatsOverviewWidget as BaseWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

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

    protected function getStats(): array
    {
        // 1. Online Users (Active in last 5 minutes)
        // Note: Needs 'database' session driver
        $onlineCount = DB::table('sessions')
            ->where('last_activity', '>=', now()->subMinutes(5)->getTimestamp())
            ->count();

        // 2. Conversion Ratio (Leads to Orders)
        $totalLeads = Lead::count();
        $totalOrders = Order::count();
        $conversionRate = $totalLeads > 0 ? round(($totalOrders / $totalLeads) * 100, 1) : 0;

        // 3. Revenue
        $totalRevenue = Order::where('payment_status', 'paid')->sum('total_amount');

        return [
            Stat::make('Active Users Now', $onlineCount)
                ->description('Users online in the last 5 minutes')
                ->descriptionIcon('heroicon-m-users')
                ->color('success')
                ->chart([7, 10, 5, 12, 10, 14, 18]),

            Stat::make('Total Leads', $totalLeads)
                ->description(Lead::whereDate('created_at', Carbon::today())->count() . ' new today')
                ->descriptionIcon('heroicon-m-user-plus')
                ->chart([3, 5, 2, 8, 4, 10, 12])
                ->color('warning'),

            Stat::make('Total Orders', $totalOrders)
                ->description($conversionRate . '% conversion rate')
                ->descriptionIcon('heroicon-m-shopping-bag')
                ->chart([1, 4, 2, 6, 8, 12, 15])
                ->color('info'),

            Stat::make('Paid Revenue', 'PKR ' . number_format($totalRevenue))
                ->description('Total settled payments')
                ->descriptionIcon('heroicon-m-currency-dollar')
                ->color('success'),
        ];
    }
}
