<?php

namespace App\Filament\Widgets;

use App\Models\Coupon;
use App\Models\CouponRedemption;
use Filament\Tables\Columns\TextColumn;
use Filament\Widgets\TableWidget as BaseWidget;
use Illuminate\Database\Eloquent\Builder;

class CouponUsageWidget extends BaseWidget
{
    protected static ?int $sort = 7;

    protected function getHeading(): string
    {
        return __('Coupon performance (30d)');
    }

    protected function getTableQuery(): Builder
    {
        $since = now()->subDays(30);

        return Coupon::query()
            ->withCount(['redemptions as recent_redemptions_count' => function (Builder $query) use ($since) {
                $query->where('status', CouponRedemption::STATUS_SUCCESS)
                    ->where('redeemed_at', '>=', $since);
            }])
            ->withSum(['redemptions as recent_discount_sum' => function (Builder $query) use ($since) {
                $query->where('status', CouponRedemption::STATUS_SUCCESS)
                    ->where('redeemed_at', '>=', $since);
            }], 'amount_discounted')
            ->orderByDesc('recent_discount_sum')
            ->limit(5);
    }

    protected function getTableColumns(): array
    {
        return [
            TextColumn::make('code')
                ->label(__('Code'))
                ->badge(),
            TextColumn::make('status')
                ->label(__('Status'))
                ->badge(),
            TextColumn::make('recent_redemptions_count')
                ->label(__('Uses (30d)'))
                ->sortable(),
            TextColumn::make('recent_discount_sum')
                ->label(__('Discount (30d)'))
                ->formatStateUsing(function ($state, Coupon $record) {
                    $currency = $record->currency ?? 'EUR';
                    $value = (float) ($state ?? 0);

                    return sprintf('%s %0.2f', $currency, $value);
                })
                ->sortable(),
        ];
    }
}
