<?php

namespace App\Filament\Widgets;

use App\Filament\Resources\InvoiceResource;
use App\Filament\Support\StatusLookup;
use App\Models\Lookups\Status;
use App\Models\Sales\Invoice;
use App\Services\CurrentContext;
use Filament\Actions\Action;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Filament\Widgets\TableWidget;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;

/**
 * The ten most recent invoices for the selected branch, from
 * IsmsDashboardController::index().
 */
class RecentInvoicesWidget extends TableWidget
{
    protected static ?int $sort = 4;

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

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

    public function table(Table $table): Table
    {
        $branchId = app(CurrentContext::class)->branchId();

        return $table
            ->heading('Recent invoices')
            ->query(
                fn (): Builder => Invoice::query()
                    ->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
                    ->with(['customer:id,business_name', 'paymentStatus:id,code,name,color'])
                    ->latest('created_at')
                    ->limit(10)
            )
            // The source caps this list at 10 with no pagination.
            ->paginated(false)
            ->columns([
                TextColumn::make('invoice_number')->label('Invoice #')->badge(),
                TextColumn::make('customer.business_name')->label('Customer')->placeholder('Walk-in'),
                TextColumn::make('channel')->badge()->color('gray'),
                TextColumn::make('net_total')->money(fn () => app(CurrentContext::class)->currencyCode()),
                TextColumn::make('balance')->money(fn () => app(CurrentContext::class)->currencyCode()),
                TextColumn::make('paymentStatus.name')
                    ->label('Payment')
                    ->badge()
                    ->color(fn (Invoice $record): string => StatusLookup::colorOf(Status::CTX_INVOICE_PAYMENT, $record->paymentStatus?->code ?? '')),
                TextColumn::make('created_at')->dateTime()->since(),
            ])
            ->recordActions([
                Action::make('view')
                    ->url(fn (Invoice $record): string => InvoiceResource::getUrl('view', ['record' => $record]))
                    ->visible(fn (Invoice $record): bool => InvoiceResource::canView($record)),
            ]);
    }
}
