<?php

namespace App\Filament\Widgets;

use App\Models\SiteActivity;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Widgets\TableWidget as BaseWidget;
use Illuminate\Support\Facades\DB;

class PerformanceWidget extends BaseWidget
{
    public function getHeading(): ?string
    {
        return 'Content Performance (Views & Clicks)';
    }
    protected static ?int $sort = 6;
    protected int | string | array $columnSpan = 'full';

    public function table(Table $table): Table
    {
        return $table
            ->query(
                SiteActivity::query()
                    ->select(
                        DB::raw("COALESCE(target_type, '') || '-' || COALESCE(target_id, '') as id"),
                        'target_type', 
                        'target_id', 
                        DB::raw('count(*) as total_actions')
                    )
                    ->whereNotNull('target_type')
                    ->whereNotNull('target_id')
                    ->groupBy('target_type', 'target_id')
                    ->orderByDesc('total_actions')
            )
            ->columns([
                Tables\Columns\TextColumn::make('target_type')
                    ->label('Entity Type')
                    ->badge()
                    ->formatStateUsing(fn ($state) => ucfirst($state)),
                Tables\Columns\TextColumn::make('target_id')
                    ->label('Slug/ID')
                    ->weight('bold'),
                Tables\Columns\TextColumn::make('total_actions')
                    ->label('Total Interactions')
                    ->numeric()
                    ->alignEnd()
                    ->color('success')
                    ->weight('bold'),
            ])
            ->paginated(false);
    }
}
