<?php

namespace App\Filament\Resources\UserResource\Widgets;

use App\Models\NotificationLog;
use App\Models\User;
use Filament\Widgets\StatsOverviewWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;

class MissedNotificationsOverview extends StatsOverviewWidget
{
    public ?User $record = null;

    protected function getStats(): array
    {
        if ($this->record === null) {
            return [];
        }

        $userId = $this->record->id;

        $missedTodayByChannel = fn (string $channel): int => NotificationLog::where('user_id', $userId)
            ->where('channel', $channel)
            ->where('sent', false)
            ->whereDate('created_at', today())
            ->count();

        $missedThisMonth = NotificationLog::where('user_id', $userId)
            ->where('sent', false)
            ->whereMonth('created_at', now()->month)
            ->whereYear('created_at', now()->year)
            ->count();

        return [
            Stat::make('SMS missed today', $missedTodayByChannel('sms'))
                ->color($missedTodayByChannel('sms') > 0 ? 'warning' : 'gray'),
            Stat::make('WhatsApp missed today', $missedTodayByChannel('whatsapp'))
                ->color($missedTodayByChannel('whatsapp') > 0 ? 'warning' : 'gray'),
            Stat::make('Total missed this month', $missedThisMonth)
                ->color($missedThisMonth > 0 ? 'warning' : 'gray'),
        ];
    }
}
