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

    protected int | string | array $columnSpan = 1;

    protected static ?int $sort = 6;

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

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

    public function table(Table $table): Table
    {
        return $table
            ->heading(static::getCountsHeading())
            ->queryStringIdentifier('orders_by_province')
            ->query(
                $this->applyOrdersListDateFilter(
                    Order::query()
                    ->whereNotNull('province_id')
                    ->join('tbl_provinces', 'tbl_orders.province_id', '=', 'tbl_provinces.id_province')
                    ->selectRaw('MIN(tbl_orders.id_order) as id_order, tbl_provinces.name as province_name, COUNT(*) as total')
                    ->groupBy('tbl_provinces.name')
                    ->orderByDesc('total')
                )
            )
            ->columns([
                Tables\Columns\TextColumn::make('province_name')
                    ->label('Provincia')
                    ->wrap(),
                Tables\Columns\TextColumn::make('total')
                    ->label('Cantidad')
                    ->numeric()
                    ->sortable(),
            ])
            ->paginated(false);
    }
}
