<?php

namespace App\Exports;

use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use Illuminate\Contracts\View\View;
use Maatwebsite\Excel\Concerns\FromView;
use Maatwebsite\Excel\Concerns\WithStyles;

class ParameterSubDistrictExport implements FromView, WithStyles
{
    /**
     * @return \Illuminate\Support\Collection
     */

    protected $parameterSubDistrict;

    public function __construct($parameterSubDistrict)
    {
        $this->parameterSubDistrict = $parameterSubDistrict;
    }

    public function view(): View
    {
        $excelData = [];

        foreach ($this->parameterSubDistrict as $subDistrict => $data) {
            $weatherData = $data[1];
            foreach ($weatherData as $parameter => $values) {
                $row = [
                    'year' => $data[0],
                    'sub_district' => $subDistrict,
                    'parameter' => $parameter
                ];

                for ($i = 0; $i < 12; $i++) {
                    if ($i + 1 < 10) {
                        $row["bulan " . ($i + 1)] = $values[$data[0] . '0' . ($i + 1)] ?? '-';
                    } else {
                        $row["bulan " . ($i + 1)] = $values[$data[0] . ($i + 1)] ?? '-';
                    }
                }

                $excelData[] = $row;
            }
        }

        return view('website.export.excel-parameter-sub-district', [
            'parameterSubDistrict' => $excelData,
        ]);
    }

    public function styles(Worksheet $sheet)
    {
        $highestColumn = $sheet->getHighestColumn();
        $highestColumnIndex = Coordinate::columnIndexFromString($highestColumn);

        for ($col = 1; $col <= $highestColumnIndex; $col++) {
            $columnLetter = Coordinate::stringFromColumnIndex($col);
            $sheet->getColumnDimension($columnLetter)->setAutoSize(true);
        }
    }
}
