<?php

namespace App\Filament\Tables\Filters;

use Carbon\Carbon;
use Filament\Forms\Components\DatePicker;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Filters\Indicator;
use Illuminate\Database\Eloquent\Builder;

class CreatedAtDateFilter
{
    public static function make(): Filter
    {
        return Filter::make('created_at')
            ->label(__('filament.filters.date'))
            ->schema([
                DatePicker::make('from')
                    ->label(__('filament.filters.from')),
                DatePicker::make('until')
                    ->label(__('filament.filters.until')),
            ])
            ->query(function (Builder $query, array $data): Builder {
                return $query
                    ->when(
                        $data['from'] ?? null,
                        fn (Builder $query, string $date): Builder => $query->whereDate('created_at', '>=', $date),
                    )
                    ->when(
                        $data['until'] ?? null,
                        fn (Builder $query, string $date): Builder => $query->whereDate('created_at', '<=', $date),
                    );
            })
            ->indicateUsing(function (array $data): array {
                $indicators = [];

                if ($data['from'] ?? null) {
                    $indicators[] = Indicator::make(__('filament.filters.from_indicator', [
                        'date' => Carbon::parse($data['from'])->toFormattedDateString(),
                    ]))
                        ->removeField('from');
                }

                if ($data['until'] ?? null) {
                    $indicators[] = Indicator::make(__('filament.filters.until_indicator', [
                        'date' => Carbon::parse($data['until'])->toFormattedDateString(),
                    ]))
                        ->removeField('until');
                }

                return $indicators;
            });
    }
}
