<?php

// ── FILE 3 ────────────────────────────────────────────────
// app/Filament/Resources/Expenses/Tables/ExpensesTable.php

namespace App\Filament\Resources\Expenses\Tables;

use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteBulkAction;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;

class ExpensesTable
{
    public static function configure(Table $table): Table
    {
        return $table
            ->modifyQueryUsing(fn ($query) =>
                $query->select([
                    'id', 'category', 'amount', 'currency',
                    'description', 'expense_date', 'created_at',
                ])
                ->latest('expense_date')
            )
            ->paginated([15, 25, 50])
            ->columns([
                TextColumn::make('expense_date')
                    ->label('Date')
                    ->date('M d, Y')
                    ->sortable(),

                TextColumn::make('category')
                    ->searchable()
                    ->weight('bold'),

                TextColumn::make('amount')
                    ->formatStateUsing(fn ($record) =>
                        $record->currency . ' ' . number_format($record->amount, 2)
                    )
                    ->weight('bold')
                    ->color('danger'),

                TextColumn::make('currency')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'USD' => 'info',
                        default => 'gray',
                    }),

                TextColumn::make('description')
                    ->limit(40)
                    ->placeholder('—'),
            ])
            ->filters([
                SelectFilter::make('currency')
                    ->options(['KES' => 'KES', 'USD' => 'USD']),

                Filter::make('this_month')
                    ->label('This Month')
                    ->query(fn ($query) =>
                        $query->whereMonth('expense_date', now()->month)
                              ->whereYear('expense_date', now()->year)
                    )
                    ->default(),
            ])
            ->actions([
                EditAction::make()
                    ->visible(fn (): bool =>
                        auth()->user()?->hasPermissionTo('edit_expenses') ?? false
                    ),
                DeleteAction::make()
                    ->visible(fn (): bool =>
                        auth()->user()?->hasPermissionTo('delete_expenses') ?? false
                    ),
            ])
            ->bulkActions([
                BulkActionGroup::make([
                    DeleteBulkAction::make(),
                ]),
            ])
            ->defaultSort('expense_date', 'desc');
    }
}