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

    protected int | string | array $columnSpan = 1;

    protected static ?int $sort = 9;

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

    public function table(Table $table): Table
    {
        return $table
            ->heading('Órdenes por distrito')
            ->queryStringIdentifier('orders_by_district')
            ->query(
                $this->applyOrdersListDateFilter(
                    Order::query()
                        ->whereNotNull('district_id')
                        ->join('tbl_districts', 'tbl_orders.district_id', '=', 'tbl_districts.id_district')
                        ->selectRaw('MIN(tbl_orders.id_order) as id_order, tbl_districts.name as district_name, COUNT(*) as total')
                        ->groupBy('tbl_districts.name')
                        ->orderByDesc('total')
                )
            )
            ->columns([
                Tables\Columns\TextColumn::make('district_name')
                    ->label('Distrito')
                    ->wrap(),
                Tables\Columns\TextColumn::make('total')
                    ->label('Cantidad')
                    ->numeric()
                    ->sortable(),
            ])
            ->paginated(false);
    }
}
