<?php

namespace App\Exports;

use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithStyles;
use Maatwebsite\Excel\Concerns\WithTitle;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class StyledReportExport implements FromCollection, WithTitle, ShouldAutoSize, WithStyles
{
    /**
     * @param  list<string>  $headings
     * @param  list<list<mixed>>  $rows
     * @param  array<string, mixed>  $meta
     */
    public function __construct(
        private readonly string $title,
        private readonly array $headings,
        private readonly array $rows,
        private readonly array $meta = [],
    ) {}

    public function collection(): Collection
    {
        $lines = collect([
            [$this->meta['company'] ?? config('southend.app_name')],
            [$this->title],
            ['Exported: '.($this->meta['exported_at'] ?? now()->format('d M Y H:i'))],
        ]);

        if (! empty($this->meta['filters'])) {
            $lines->push(['Filters: '.$this->meta['filters']]);
        }

        if (! empty($this->meta['totals'])) {
            $lines->push(['Totals: '.$this->meta['totals']]);
        }

        $lines->push(['']);
        $lines->push($this->headings);

        return $lines->concat(collect($this->rows));
    }

    public function title(): string
    {
        return mb_substr($this->title, 0, 31);
    }

    public function styles(Worksheet $sheet): array
    {
        $headerRow = 5
            + (empty($this->meta['filters']) ? 0 : 1)
            + (empty($this->meta['totals']) ? 0 : 1)
            + 1;

        return [
            1 => ['font' => ['bold' => true, 'size' => 14]],
            2 => ['font' => ['bold' => true]],
            $headerRow => ['font' => ['bold' => true], 'fill' => ['fillType' => 'solid', 'startColor' => ['rgb' => 'E5E7EB']]],
        ];
    }
}
