<?php

namespace App\Filament\Association\Widgets;

use App\Models\Payment;
use Filament\Widgets\Widget;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

class RecentActivityWidget extends Widget
{
    protected static string $view = 'filament.association.widgets.recent-activity';

    protected static ?int $sort = 6;

    protected int | string | array $columnSpan = 1;

    public function getActivities(): Collection
    {
        $associationId = filament()->getTenant()->id;

        // Recent payments
        $payments = Payment::where('association_id', $associationId)
            ->where('status', 'completed')
            ->with('user:id,firstname,surname')
            ->latest('paid_at')
            ->limit(5)
            ->get()
            ->map(fn ($p) => [
                'type' => 'payment',
                'icon' => 'heroicon-o-banknotes',
                'color' => 'success',
                'description' => ($p->user ? trim($p->user->firstname . ' ' . $p->user->surname) : 'Member') . ' paid ' . number_format($p->amount, 2),
                'time' => $p->paid_at,
            ]);

        // New members
        $newMembers = DB::table('association_user')
            ->join('users', 'association_user.user_id', '=', 'users.id')
            ->where('association_user.association_id', $associationId)
            ->orderByDesc('association_user.joined_at')
            ->limit(5)
            ->select(['users.firstname', 'users.surname', 'association_user.joined_at'])
            ->get()
            ->map(fn ($m) => [
                'type' => 'member',
                'icon' => 'heroicon-o-user-plus',
                'color' => 'info',
                'description' => trim($m->firstname . ' ' . $m->surname) . ' joined the association',
                'time' => $m->joined_at ? \Carbon\Carbon::parse($m->joined_at) : null,
            ]);

        // Merge, sort by time, take 10
        return $payments->concat($newMembers)
            ->filter(fn ($item) => $item['time'] !== null)
            ->sortByDesc('time')
            ->take(10)
            ->values();
    }
}
