<?php

namespace App\Filament\Resources\OrderResource\Widgets;

use App\Filament\Resources\OrderResource\Widgets\Concerns\AppliesOrdersListDateFilter;
use App\Models\Order;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Widgets\TableWidget;

class OrdersByStoreWidget extends TableWidget
{
    use AppliesOrdersListDateFilter;

    protected int | string | array $columnSpan = 1;

    protected static ?int $sort = 7;

    public static function canView(): bool
    {
        return auth()->user()?->can('orders.view') ?? false;
    }

    public static function getCountsHeading(): string
    {
        return 'Reporte: Órdenes por tienda';
    }

    public function table(Table $table): Table
    {
        return $table
            ->heading(static::getCountsHeading())
            ->queryStringIdentifier('orders_by_store')
            ->query(
                $this->applyOrdersListDateFilter(
                    Order::query()
                    ->selectRaw('MIN(id_order) as id_order, store_name, COUNT(*) as total')
                    ->groupBy('store_name')
                    ->orderByDesc('total')
                )
            )
            ->columns([
                Tables\Columns\TextColumn::make('store_name')
                    ->label('Tienda')
                    ->formatStateUsing(fn (?string $state) => filled($state) ? $state : 'Sin tienda')
                    ->wrap(),
                Tables\Columns\TextColumn::make('total')
                    ->label('Cantidad')
                    ->numeric()
                    ->sortable(),
            ])
            ->paginated(false);
    }
}
