<?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;
use Maatwebsite\Excel\Concerns\WithCustomCsvSettings;

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

    /**
     * @return Collection
     */
    public function collection(): 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 [];
    }

    public function getCsvSettings(): array
    {
        if ($this->exportMap->format !== 'csv') {
            return [];
        }

        return [
            'delimiter' => $this->exportMap->getDelimiter(),
        ];
    }
}
