<?php

namespace App\Filament\Widgets;

use App\Models\Payment;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Widgets\TableWidget as BaseWidget;
use Illuminate\Database\Eloquent\Builder;

class GatewayPerformance extends BaseWidget
{
    protected static ?string $heading = 'Gateway Performance';

    protected static ?int $sort = 3;

    public function table(Table $table): Table
    {
        return $table
            ->query($this->query())
            ->columns([
                Tables\Columns\TextColumn::make('gateway.display_name')
                    ->label('Gateway')
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('payments_count')
                    ->label('# Payments')
                    ->sortable(),
                Tables\Columns\TextColumn::make('total_amount')
                    ->label('Volume')
                    ->money(fn ($record) => $record->currency ?? 'USD')
                    ->sortable(),
                Tables\Columns\TextColumn::make('capture_rate')
                    ->label('Capture %')
                    ->formatStateUsing(fn ($state) => number_format($state, 1).' %'),
            ]);
    }

    protected function query(): Builder
    {
        return Payment::query()
            ->with('gateway')
            ->selectRaw('payment_gateway_id, COUNT(*) as payments_count, SUM(amount) as total_amount, SUM(status = "captured") / COUNT(*) * 100 as capture_rate, MAX(currency) as currency')
            ->groupBy('payment_gateway_id');
    }
}
