<?php

namespace App\Filament\Widgets\Executive;

use App\Models\Attendance;
use App\Models\User;
use Carbon\Carbon;
use Filament\Widgets\ChartWidget;

class DepartmentStatsWidget extends ChartWidget
{
    protected static ?string $heading = 'Kehadiran per Departemen';

    protected static ?string $description = 'Distribusi kehadiran berdasarkan departemen bulan ini';

    protected static ?int $sort = 4;

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

    protected static ?string $maxHeight = '300px';

    protected function getData(): array
    {
        $thisMonth = now()->month;
        $thisYear = now()->year;

        $departments = User::where('is_active', true)
            ->whereDoesntHave('roles', fn ($q) => $q->where('name', 'super_admin'))
            ->whereNotNull('department')
            ->distinct()
            ->pluck('department')
            ->toArray();

        $labels = [];
        $data = [];

        foreach ($departments as $dept) {
            $attendanceCount = Attendance::whereMonth('date', $thisMonth)
                ->whereYear('date', $thisYear)
                ->whereIn('status', ['present', 'late', 'wfh', 'business_trip'])
                ->whereHas('user', fn ($q) => $q->where('department', $dept))
                ->count();

            if ($attendanceCount > 0) {
                $labels[] = $dept ?? 'Tidak Ada';
                $data[] = $attendanceCount;
            }
        }

        return [
            'datasets' => [
                [
                    'label' => 'Kehadiran',
                    'data' => $data,
                    'backgroundColor' => [
                        'rgba(181, 109, 160, 0.8)', // Nizhamia Magenta
                        'rgba(91, 168, 181, 0.8)',  // Nizhamia Teal
                        'rgba(232, 210, 74, 0.8)',  // Nizhamia Gold
                        'rgba(34, 197, 94, 0.8)',   // Success Green
                        'rgba(59, 130, 246, 0.8)',  // Info Blue
                        'rgba(168, 85, 247, 0.8)',  // Purple
                    ],
                ],
            ],
            'labels' => $labels,
        ];
    }

    protected function getType(): string
    {
        return 'doughnut';
    }
}
