<?php

namespace App\Exports;

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

class EndOfMonth implements FromCollection, ShouldAutoSize, WithTitle, WithStyles
{
    protected $data;
    protected $sectionHeadings;

    public function __construct(array $data, array $sectionHeadings)
    {
        $this->data = $data;
        $this->sectionHeadings = $sectionHeadings;
    }

    public function collection()
    {
        $collection = new Collection();

        foreach ($this->data as $section) {
            $collection->push([strtoupper($section['section'])]);
            $collection->push($section['headings']);
            foreach ($section['data'] as $row) {
                $collection->push(array_values($row));
            }
            $collection->push([[]]);
            $collection->push([[]]);
        }

        return $collection;
    }

    public function title(): string
    {
        return 'End Of Month Analysis';
    }

    public function styles(Worksheet $sheet)
    {
        $styles = [];
        $currentRow = 1;

        foreach ($this->data as $section) {
            // Apply styles to the section title
            $styles[$currentRow] = [
                'font' => [
                    'bold' => true,
                    'size' => 14,
                    'color' => ['argb' => 'FF0000FF'], // Blue color
                ],
                'alignment' => [
                    'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
                ],
            ];

            $currentRow++; // Move to the next row (headings row)
            $currentRow += count($section['data']) + 3; // Move past the headings and data rows, including extra space
        }

        return $styles;
    }
}
