<?php

namespace App\Filament\Exports;

use App\Models\AlertMailRule;
use App\Models\Plant;
use Filament\Actions\Exports\ExportColumn;
use Filament\Actions\Exports\Exporter;
use Filament\Actions\Exports\Models\Export;

class AlertMailRuleExporter extends Exporter
{
    protected static ?string $model = AlertMailRule::class;

    public static function getColumns(): array
    {
        static $rowNumber = 0;
        return [
            ExportColumn::make('no')
                ->label('NO')
                ->state(function ($record) use (&$rowNumber) {
                    // Increment and return the row number
                    return ++$rowNumber;
                }),
            ExportColumn::make('module')
            ->label('MODULE'),
            ExportColumn::make('rule_name')
            ->label('RULE NAME'),
            ExportColumn::make('email')
            ->label('EMAIL'),
            ExportColumn::make('schedule_type')
            ->label('SCHEDULE TYPE'),
            ExportColumn::make('plant')
            ->label('PLANT CODE')
            ->formatStateUsing(function ($state) {
                // $state is the plant ID from the database
                if ($state == 0) {
                    return 'All Plants';
                }

                $plant = Plant::find($state);
                return $plant ? $plant->code : 'Unknown';
            }),
            ExportColumn::make('machine.work_center')
            ->label('WORK CENTER'),
            ExportColumn::make('cc_emails')
            ->label('CC EMAILS'),
            ExportColumn::make('invoiceMaster.receiving_plant_name')
            ->label('RECEIVING PLANT NAME'),
            ExportColumn::make('invoiceMaster.transport_name')
            ->label('TRANSPORT NAME'),
            ExportColumn::make('created_at')
            ->label('CREATED AT'),
            ExportColumn::make('created_by')
            ->label('CREATED BY'),
            ExportColumn::make('updated_at')
            ->label('UPDATED AT'),
            ExportColumn::make('deleted_at')
            ->label('DELETED AT')
            ->enabledByDefault(false),

        ];
    }

    public static function getCompletedNotificationBody(Export $export): string
    {
        $body = 'Your alert mail rule 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;
    }
}
