<?php

namespace App\Filament\Exports;

use App\Models\Sales\SalesOrderItem;
use Filament\Actions\Exports\ExportColumn;
use Filament\Actions\Exports\Exporter;
use Filament\Actions\Exports\Models\Export;
use Illuminate\Support\Number;

/**
 * Columns mirror CustomOrderResource::table(). The full specification text is
 * included rather than truncated — the export is what gets handed to whoever
 * is actually making the item, so the customer's exact wording has to survive.
 */
class CustomOrderExporter extends Exporter
{
    protected static ?string $model = SalesOrderItem::class;

    public static function getColumns(): array
    {
        return [
            ExportColumn::make('salesOrder.order_number')->label('Order #'),
            ExportColumn::make('product_name')->label('Item'),
            ExportColumn::make('custom_description')->label('Description'),
            ExportColumn::make('custom_specification')->label('Exact details'),
            ExportColumn::make('salesOrder.customer.business_name')->label('Customer'),
            ExportColumn::make('salesOrder.customer.phone')->label('Phone'),
            ExportColumn::make('salesOrder.branch.name')->label('Branch'),
            ExportColumn::make('quantity'),
            ExportColumn::make('unit.code')->label('Unit'),
            ExportColumn::make('unit_price')->label('Unit price'),
            ExportColumn::make('line_total')->label('Line total'),
            ExportColumn::make('salesOrder.status.name')->label('Order status'),
            ExportColumn::make('salesOrder.order_date')->label('Ordered'),
            ExportColumn::make('salesOrder.deadline_date')->label('Deadline'),
        ];
    }

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