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

    protected int | string | array $columnSpan = 1;

    protected static ?int $sort = 8;

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

    public function table(Table $table): Table
    {
        return $table
            ->heading('Órdenes por cantón')
            ->queryStringIdentifier('orders_by_canton')
            ->query(
                $this->applyOrdersListDateFilter(
                    Order::query()
                        ->whereNotNull('canton_id')
                        ->join('tbl_cantons', 'tbl_orders.canton_id', '=', 'tbl_cantons.id_canton')
                        ->selectRaw('MIN(tbl_orders.id_order) as id_order, tbl_cantons.name as canton_name, COUNT(*) as total')
                        ->groupBy('tbl_cantons.name')
                        ->orderByDesc('total')
                )
            )
            ->columns([
                Tables\Columns\TextColumn::make('canton_name')
                    ->label('Cantón')
                    ->wrap(),
                Tables\Columns\TextColumn::make('total')
                    ->label('Cantidad')
                    ->numeric()
                    ->sortable(),
            ])
            ->paginated(false);
    }
}
