<?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 ParameterVillageExport implements FromView, WithStyles
{
    /**
     * @return \Illuminate\Support\Collection
     */

    protected $parameterVillage;

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

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

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

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

                $excelData[] = $row;
            }
        }

        return view('website.export.excel-parameter-village', [
            'parameterVillage' => $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);
        }
    }
}
