<?php

namespace App\Filament\Resources\QrcodeRecords\Tables;

use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Filament\Tables\Filters\Filter;
use Filament\Forms\Components\DatePicker;
use Illuminate\Database\Eloquent\Builder;

class QrcodeRecordsTable
{
    public static function configure(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('outlet_id')
                    ->searchable()
                    ->label('店號'),
                TextColumn::make('outlet_name')
                    ->searchable()
                    ->label('店名'),

                TextColumn::make('representative_id')
                    ->searchable()
                    ->label('Representative ID'),
                TextColumn::make('qr_generated_at')
                    ->dateTime()
                    ->sortable()
                    ->label('QR Code 產生時間'),
                TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('updated_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Filter::make('qr_generated_at')
                    ->form([
                        DatePicker::make('from')->label('開始日期'),
                        DatePicker::make('until')->label('結束日期'),
                    ])
                    ->query(function (Builder $query, array $data) {
                        return $query
                            ->when($data['from'], fn ($q) => $q->whereDate('qr_generated_at', '>=', $data['from']))
                            ->when($data['until'], fn ($q) => $q->whereDate('qr_generated_at', '<=', $data['until']));
                    }),
            ])
            ->recordActions([
                EditAction::make(),
            ])
            ->toolbarActions([
                BulkActionGroup::make([
                    DeleteBulkAction::make(),
                ]),
            ])
            ->searchPlaceholder('請輸入店號、店名或 Representative ID 進行搜尋');
    }
}
