<?php

namespace App\Exports;

use App\Models\ExportMap;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\App;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithStrictNullComparison;

class MapExport implements FromCollection, WithHeadings, ShouldAutoSize, WithStrictNullComparison
{
    public function __construct(protected Collection $data, protected ExportMap $exportMap)
    {
        //
    }

    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return $this->data;
    }

    /**
     * Heading row
     *
     * @return string[]
     */
    public function headings(): array
    {
        if ($this->exportMap->include_header_row) {
            $columns = App::make(config('export_maps.types.' . $this->exportMap->type))->columns();
            return $this->data->first()
                ?->map(fn ($value, $key) => $columns[$key] ?? $key)
                ->toArray() ?? [];
        }

        return [];
    }
}
