<?php

namespace App\Filament\Widgets;

use App\Models\CustomerDocument;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Widgets\TableWidget as BaseWidget;

class ExpiringDocumentsWidget extends BaseWidget
{
    protected static ?string $heading = 'اسناد نزدیک به انقضا';
    protected int|string|array $columnSpan = 'full';
    protected static ?int $sort = 9;

    public static function canView(): bool
    {
        $user = auth()->user();

        return $user?->can('view_reports')
            && $user->canSeeAll('customers')
            && CustomerDocument::whereNotNull('expires_at')
                ->whereDate('expires_at', '<=', now()->addDays(30))->exists();
    }

    public function table(Table $table): Table
    {
        return $table
            ->query(
                CustomerDocument::query()
                    ->whereNotNull('expires_at')
                    ->whereDate('expires_at', '<=', now()->addDays(30))
                    ->orderBy('expires_at')
            )
            ->columns([
                Tables\Columns\TextColumn::make('customer.display_name')->label('مشتری'),
                Tables\Columns\TextColumn::make('title')->label('سند'),
                Tables\Columns\TextColumn::make('type')->label('نوع')->badge()
                    ->formatStateUsing(fn ($state) => [
                        'contract' => 'قرارداد', 'identity' => 'مدارک هویتی', 'license' => 'مجوز',
                        'insurance' => 'بیمه‌نامه', 'other' => 'سایر',
                    ][$state] ?? $state),
                Tables\Columns\TextColumn::make('expires_at')->label('تاریخ انقضا')->jalaliDate()
                    ->color(fn ($record) => $record->expires_at->isPast() ? 'danger' : 'warning'),
            ])
            ->paginated([5, 10]);
    }
}
