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

    protected int | string | array $columnSpan = 1;

    protected static ?int $sort = 3;

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

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

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