<?php

namespace App\Exports;

use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;

class GenericReportExport implements FromCollection, WithHeadings
{
    public function __construct(protected string $type, protected Collection $rows)
    {
    }

    public function collection(): Collection
    {
        return $this->rows->map(function ($row) {
            return match ($this->type) {
                'sales' => [$row->sale_number, $row->customer?->name, $row->line?->phone_number, $row->total, $row->sale_date],
                'payments' => [$row->payment_number, $row->customer?->name, $row->amount, $row->payment_method?->value, $row->date],
                'invoices' => [$row->invoice_number, $row->customer?->name, $row->total, $row->status?->value, $row->date],
                default => [$row->id, $row->name ?? $row->phone_number ?? $row->invoice_number ?? ''],
            };
        });
    }

    public function headings(): array
    {
        return match ($this->type) {
            'sales' => ['Sale', 'Customer', 'Line', 'Total', 'Date'],
            'payments' => ['Payment', 'Customer', 'Amount', 'Method', 'Date'],
            'invoices' => ['Invoice', 'Customer', 'Total', 'Status', 'Date'],
            default => ['ID', 'Name'],
        };
    }
}
