<?php

namespace App\Filament\Exports;

use App\Models\AssistanceApplication;
use Filament\Actions\Exports\ExportColumn;
use Filament\Actions\Exports\Exporter;
use Filament\Actions\Exports\Models\Export;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Number;

class AssistanceApplicationExporter extends Exporter
{
    protected static ?string $model = AssistanceApplication::class;

    public static function getColumns(): array
    {
        return [
            // Application fields
            ExportColumn::make('id')
                ->label('Application ID'),
            ExportColumn::make('created_at')
                ->label('Submitted Date')
                ->formatStateUsing(fn ($state) => $state?->format('Y-m-d H:i:s')),
            ExportColumn::make('updated_at')
                ->label('Last Updated')
                ->formatStateUsing(fn ($state) => $state?->format('Y-m-d H:i:s')),
            ExportColumn::make('status')
                ->label('Status'),

            // User fields
            ExportColumn::make('user.name')
                ->label('User Name')
                ->formatStateUsing(fn ($state) => $state ?? 'N/A'),
            ExportColumn::make('user.email')
                ->label('User Email')
                ->formatStateUsing(fn ($state) => $state ?? 'N/A'),
            ExportColumn::make('user.phone')
                ->label('User Phone')
                ->formatStateUsing(fn ($state) => $state ?? 'N/A'),
            ExportColumn::make('user.full_address')
                ->label('User Address')
                ->formatStateUsing(fn ($state) => $state ?: 'N/A'),

            // Form answers as JSON
            ExportColumn::make('form_answers')
                ->label('Form Answers (JSON)')
                ->state(function (AssistanceApplication $record): string {
                    return $record->answers->map(function ($answer) {
                        return [
                            'question' => $answer->question_label,
                            'answer' => $answer->formatted_answer,
                        ];
                    })->toJson();
                }),
        ];
    }

    public static function modifyQuery(Builder $query): Builder
    {
        // Eager load relationships to prevent N+1 queries
        return $query->with([
            'user',
            'answers',
        ]);
    }

    public static function getCompletedNotificationBody(Export $export): string
    {
        $body = 'Your assistance application export has completed and '.Number::format($export->successful_rows).' '.str('row')->plural($export->successful_rows).' exported.';

        if ($failedRowsCount = $export->getFailedRowsCount()) {
            $body .= ' '.Number::format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to export.';
        }

        return $body;
    }
}
