<?php

namespace App\Exports;

use Illuminate\Support\Collection;
use Illuminate\Support\Enumerable;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithStrictNullComparison;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class YearlyEnquiryExport implements FromCollection, WithHeadings, ShouldAutoSize, WithStrictNullComparison, WithStyles
{
    public function __construct(protected Collection $data)
    {
        //
    }

    public function collection(): Enumerable
    {
        return $this->data->map(function ($row, $name) {
            if ($row instanceof Collection) {
                $row = $row->toArray();
            }
            array_unshift($row, $name);
            return $row;
        });
    }

    /**
     * Heading row
     *
     * @return string[]
     */
    public function headings(): array
    {
        $data = array_keys($this->data->first());
        array_unshift($data, '');
        return $data;
    }

    public function styles(Worksheet $sheet)
    {
        $last_row = $this->data->count() + 1;
        $sheet->getStyle('A1:N1')->getFont()->setBold(true);
        $sheet->getStyle('A1:A' . $last_row)->getFont()->setBold(true);
        $sheet->setAutoFilter('B1:N1');
        $sheet->setSelectedCell('A1');
    }
}
