<?php

namespace App\Filament\Widgets;

use App\Models\Inventory\Damage;
use App\Models\Returns\ReturnDoc;
use App\Models\Sales\Invoice;
use App\Services\CurrentContext;
use Carbon\Carbon;
use Filament\Widgets\StatsOverviewWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;
use Illuminate\Support\Facades\Auth;

/**
 * The headline figures from Isms\IsmsDashboardController::index()
 * (docs/migration-plan.md Phase 11): today's sales and collections, the
 * outstanding balance, month-to-date damage cost, and the return rate.
 *
 * Branch scoping matches the source: a concrete branch when one is selected,
 * otherwise the All aggregate (which BranchScope still limits to the user's
 * accessible branches).
 */
class IsmsStatsOverview extends StatsOverviewWidget
{
    protected static ?int $sort = 1;

    protected int|string|array $columnSpan = 'full';

    public static function canView(): bool
    {
        return Auth::user()?->hasPermissionTo('dashboard.access') ?? false;
    }

    protected function getStats(): array
    {
        $branchId = app(CurrentContext::class)->branchId();
        $today = Carbon::today();
        $monthStart = Carbon::now()->startOfMonth();

        $branchInvoice = fn () => Invoice::query()->when($branchId, fn ($q) => $q->where('branch_id', $branchId));

        $totalSalesToday = (float) $branchInvoice()->whereDate('created_at', $today)->sum('net_total');
        $totalPaidToday = (float) $branchInvoice()->whereDate('created_at', $today)->sum('paid_amount');
        $totalPending = (float) $branchInvoice()->where('balance', '>', 0)->sum('balance');

        $damageCostMtd = (float) Damage::query()
            ->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
            ->where('created_at', '>=', $monthStart)
            ->sum('total_damage_cost');

        $invoicedThisMonth = (int) $branchInvoice()->where('created_at', '>=', $monthStart)->count();
        $returnsThisMonth = (int) ReturnDoc::query()
            ->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
            ->where('created_at', '>=', $monthStart)
            ->count();

        // Guarded division, exactly as the source does it.
        $returnRate = $invoicedThisMonth > 0
            ? round($returnsThisMonth / $invoicedThisMonth * 100, 2)
            : 0;

        return [
            Stat::make('Sales today', 'Rs. '.number_format($totalSalesToday, 2)),
            Stat::make('Collected today', 'Rs. '.number_format($totalPaidToday, 2)),
            Stat::make('Outstanding', 'Rs. '.number_format($totalPending, 2))
                ->color($totalPending > 0 ? 'warning' : 'success'),
            Stat::make('Damage cost (MTD)', 'Rs. '.number_format($damageCostMtd, 2))
                ->color($damageCostMtd > 0 ? 'danger' : 'gray'),
            Stat::make('Invoices (MTD)', (string) $invoicedThisMonth),
            Stat::make('Return rate (MTD)', $returnRate.'%')
                ->description($returnsThisMonth.' of '.$invoicedThisMonth),
        ];
    }
}
