<?php

namespace App\Imports;

use App\Siswa;
use App\K13HasilBelajar;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class K13HasilBelajarsImport implements ToModel, WithHeadingRow
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        $siswa = Siswa::where('nisn', $row['nisn'])
               ->where('nis', $row['nis'])->first();

        if (!$siswa)
            return null;

        $fieldMeta = [];
        foreach ($row as $key => $value) {
            if (preg_match("/\_+/", $key)) {
                $rowNames = explode('_', $key);
                if (count($rowNames) == 4)
                    $fieldMeta[$rowNames[0]][$rowNames[1]][$rowNames[2]][$rowNames[3]] = round($value, 2);
                else
                    $fieldMeta[$rowNames[0]][$rowNames[1]][$rowNames[2]] = round($value, 2);
            }
            else {
                $fieldMeta[$key] = $value;
            }
        }

        return new K13HasilBelajar([
            'siswa_id' => $siswa->id,
            'meta' => $fieldMeta,
        ]);
    }

    public function sheets(): array
    {
        return [
            new FirstSheetImport()
        ];
    }
}
