<?php

namespace App\Filament\Widgets\Executive;

use App\Models\Attendance;
use App\Models\User;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Widgets\TableWidget as BaseWidget;

class EmployeePerformanceWidget extends BaseWidget
{
    protected static ?int $sort = 3;

    protected int | string | array $columnSpan = [
        'md' => 1,
        'xl' => 1,
    ];

    protected static ?string $heading = 'Top 10 Performers Bulan Ini';

    public function table(Table $table): Table
    {
        $thisMonth = now()->month;
        $thisYear = now()->year;

        return $table
            ->query(
                User::query()
                    ->where('is_active', true)
                    ->whereDoesntHave('roles', fn ($q) => $q->where('name', 'super_admin'))
                    ->withCount([
                        'attendances as present_count' => fn ($q) => $q->whereMonth('date', $thisMonth)
                            ->whereYear('date', $thisYear)
                            ->where('status', 'present'),
                        'attendances as late_count' => fn ($q) => $q->whereMonth('date', $thisMonth)
                            ->whereYear('date', $thisYear)
                            ->where('status', 'late'),
                    ])
                    ->orderBy('present_count', 'desc')
                    ->limit(10)
            )
            ->columns([
                Tables\Columns\TextColumn::make('name')
                    ->label('Nama')
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('department')
                    ->label('Departemen')
                    ->searchable(),
                Tables\Columns\TextColumn::make('present_count')
                    ->label('Tepat Waktu')
                    ->numeric()
                    ->sortable()
                    ->color('success'),
                Tables\Columns\TextColumn::make('late_count')
                    ->label('Terlambat')
                    ->numeric()
                    ->sortable()
                    ->color('warning'),
            ])
            ->defaultSort('present_count', 'desc');
    }
}
