<?php

namespace App\Filament\Exports;

use App\Models\Activity;
use Filament\Actions\Exports\ExportColumn;
use Filament\Actions\Exports\Exporter;
use Filament\Actions\Exports\Models\Export;
use Carbon\Carbon;

class ActivityExporter extends Exporter
{
    protected static ?string $model = Activity::class;

    public static function getColumns(): array
    {
        return [
            ExportColumn::make('id')
                ->label('NO'),
            ExportColumn::make('date')
                ->label('TANGGAL')
                ->formatStateUsing(fn ($state) => $state ? Carbon::parse($state)->format('d-M-y') : ''),
            ExportColumn::make('day')
                ->label('Hari')
                ->state(fn ($record) => $record->date ? Carbon::parse($record->date)->locale('en')->dayName : ''),
            ExportColumn::make('waktu')
                ->label('WAKTU')
                ->state(function ($record) {
                    $start = $record->start_time ? Carbon::parse($record->start_time)->format('H:i') : '';
                    $end = $record->end_time ? Carbon::parse($record->end_time)->format('H:i') : '';
                    return $start && $end ? "{$start} - {$end}" : ($start ?: $end);
                }),
            ExportColumn::make('activity')
                ->label('URAIAN'),
            ExportColumn::make('output')
                ->label('OUTPUT'),
            ExportColumn::make('notes')
                ->label('KETERANGAN'),
            // Hidden columns for import reference
            ExportColumn::make('user.name')
                ->label('NAMA'),
            ExportColumn::make('user.employee_id')
                ->label('NIP'),
        ];
    }

    public static function getCompletedNotificationBody(Export $export): string
    {
        $body = 'Export aktivitas selesai. ' . number_format($export->successful_rows) . ' baris berhasil diexport.';

        if ($failedRowsCount = $export->getFailedRowsCount()) {
            $body .= ' ' . number_format($failedRowsCount) . ' baris gagal.';
        }

        return $body;
    }
}
