<?php

namespace App\Filament\Widgets;

use App\Filament\Resources\InvoiceResource;
use App\Filament\Resources\InvoiceResource\Pages\ListInvoices;
use App\Filament\Support\Kpi;
use Filament\Widgets\Concerns\InteractsWithPageTable;
use Filament\Widgets\StatsOverviewWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;
use Illuminate\Support\Facades\Auth;

/**
 * The three totals cards InvoiceController::index() computes
 * (total_sales / total_paid / total_pending), over the same ownership-scoped
 * query the listing uses — without `isms_invoices.view_all` a user's totals
 * only cover the invoices they created themselves.
 *
 * On the list page the widget is wired through HasKpiHeader, so the totals
 * react to the ACTIVE table filters (branch, customer, channel, date, status
 * tab…) rather than always covering the unfiltered query — filtering to one
 * branch changes the totals. On the dashboard — where no table props are
 * passed — it falls back to the base scoped query, which is what the
 * dashboard has always shown.
 */
class InvoiceTotalsOverview extends StatsOverviewWidget
{
    use InteractsWithPageTable;

    protected static ?int $sort = 6;

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

    /**
     * Needs `isms_invoices.access` on top of the dashboard gate every other
     * widget uses: these three cards are tenant-wide revenue figures, so a user
     * with no invoice access at all must not read them off the dashboard.
     */
    public static function canView(): bool
    {
        return (Auth::user()?->hasPermissionTo('dashboard.access') ?? false)
            && InvoiceResource::canViewAny();
    }

    protected function getTablePage(): string
    {
        return ListInvoices::class;
    }

    protected function getStats(): array
    {
        $query = $this->tableFilters !== null
            ? $this->getPageTableQuery()
            : InvoiceResource::getEloquentQuery()
                ->when(! InvoiceResource::canViewAll(), fn ($q) => $q->where('created_by', Auth::id()));

        $total = (float) $query->clone()->sum('net_total');
        $paid = (float) $query->clone()->sum('paid_amount');
        $pending = (float) $query->clone()->where('balance', '>', 0)->sum('balance');

        return [
            Kpi::money('Total sales', $total)
                ->icon('heroicon-m-receipt-percent')
                ->toStat(),
            Kpi::money('Total paid', $paid)
                ->icon('heroicon-m-banknotes')
                ->tone('success')
                ->toStat(),
            Kpi::money('Total pending', $pending)
                ->icon('heroicon-m-clock')
                ->alertWhen(fn (): bool => $pending > 0)
                ->toStat(),
        ];
    }
}
