<?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 OrdersByTypeWidget extends TableWidget
{
    use AppliesOrdersListDateFilter;

    protected int | string | array $columnSpan = 1;

    protected static ?int $sort = 2;

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

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

    public function table(Table $table): Table
    {
        return $table
            ->heading(static::getCountsHeading())
            ->queryStringIdentifier('orders_by_type')
            ->query(
                $this->applyOrdersListDateFilter(
                    Order::query()
                    ->leftJoin('tbl_order_types as t', 't.id_order_type', '=', 'tbl_orders.order_type_id')
                    ->selectRaw('MIN(tbl_orders.id_order) as id_order, tbl_orders.order_type_id, t.name as type_name, COUNT(*) as total')
                    ->groupBy('tbl_orders.order_type_id', 't.name')
                    ->orderByDesc('total')
                )
            )
            ->columns([
                Tables\Columns\TextColumn::make('type_name')
                    ->label('Tipo')
                    ->formatStateUsing(fn (?string $state) => filled($state) ? $state : '-')
                    ->wrap(),
                Tables\Columns\TextColumn::make('total')
                    ->label('Cantidad')
                    ->numeric()
                    ->sortable(),
            ])
            ->paginated(false);
    }
}
