<?php

namespace App\Filament\Widgets\HRD;

use App\Models\AttendanceCorrection;
use App\Models\EarlyLeaveRequest;
use App\Models\LateArrivalRequest;
use Filament\Widgets\Widget;

class PendingApprovalsWidget extends Widget
{
    protected static string $view = 'filament.widgets.hrd.pending-approvals-widget';

    protected static ?int $sort = 2;

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

    protected static ?string $heading = 'Pengajuan Menunggu Approval';

    public function getHeading(): string
    {
        return static::$heading ?? 'Pengajuan Menunggu Approval';
    }

    public function getPendingRequests(): array
    {
        $corrections = AttendanceCorrection::where('status', 'pending')
            ->with('user')
            ->orderBy('created_at', 'desc')
            ->limit(5)
            ->get()
            ->map(fn ($item) => [
                'id' => $item->id,
                'type' => 'correction',
                'request_type' => 'Koreksi Absen',
                'user_name' => $item->user->name ?? '-',
                'created_at' => $item->created_at,
            ]);

        $lateArrivals = LateArrivalRequest::where('status', 'pending')
            ->with('user')
            ->orderBy('created_at', 'desc')
            ->limit(5)
            ->get()
            ->map(fn ($item) => [
                'id' => $item->id,
                'type' => 'late_arrival',
                'request_type' => 'Izin Terlambat',
                'user_name' => $item->user->name ?? '-',
                'created_at' => $item->created_at,
            ]);

        $earlyLeaves = EarlyLeaveRequest::where('status', 'pending')
            ->with('user')
            ->orderBy('created_at', 'desc')
            ->limit(5)
            ->get()
            ->map(fn ($item) => [
                'id' => $item->id,
                'type' => 'early_leave',
                'request_type' => 'Izin Pulang Cepat',
                'user_name' => $item->user->name ?? '-',
                'created_at' => $item->created_at,
            ]);

        return $corrections->concat($lateArrivals)->concat($earlyLeaves)
            ->sortByDesc('created_at')
            ->take(10)
            ->values()
            ->toArray();
    }
}
