<?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) {
            $headersCount = collect($this->exportMap->headers ?? [])
                ->filter(fn($header) => !is_null($header) && !(is_string($header) && trim($header) === ''))
                ->count();

            $columnsCount = collect($this->exportMap->columns ?? [])->count();

            if ($headersCount === $columnsCount) {
                return $this->exportMap->headers ?? [];
            }

            $columns = App::make(config('export_maps.types.' . $this->exportMap->type))->columns();
            $firstRow = $this->data->first();
            return $firstRow ? collect($firstRow)
                    ->map(fn($value, $key) => $columns[$key] ?? $key)
                    ->values()
                    ->toArray() : [];
        }

        return [];
    }
}
