<?php

namespace App\Filament\Exports;

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

/**
 * Columns mirror SalesOrderResource::table(): the order's own lifecycle status
 * and its payment status side by side, plus the deadline the whole listing is
 * organised around.
 */
class SalesOrderExporter extends Exporter
{
    protected static ?string $model = SalesOrder::class;

    public static function getColumns(): array
    {
        return [
            ExportColumn::make('order_number')->label('Order #'),
            ExportColumn::make('customer.business_name')->label('Customer'),
            ExportColumn::make('customer.phone')->label('Phone'),
            ExportColumn::make('branch.name')->label('Branch'),
            ExportColumn::make('order_date')->label('Ordered'),
            ExportColumn::make('deadline_date')->label('Deadline'),
            ExportColumn::make('status.name')->label('Status'),
            ExportColumn::make('paymentStatus.name')->label('Payment status'),
            ExportColumn::make('net_total')->label('Order value'),
            ExportColumn::make('advance_paid')->label('Paid'),
            ExportColumn::make('balance'),
            ExportColumn::make('items_count')->label('Lines')->counts('items'),
            ExportColumn::make('custom_items_count')->label('Custom lines')->counts('customItems'),
            ExportColumn::make('invoice.invoice_number')->label('Invoice'),
            ExportColumn::make('creator.name')->label('Rep'),
            ExportColumn::make('created_at')->label('Created at'),
        ];
    }

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