<?php

namespace App\Imports;

use App\Models\Siswa;
use App\Models\SiswaKelas;
use App\Models\Nilai;
use App\Models\KelasMapel;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class DetailKelasImport implements ToCollection, WithHeadingRow
{
    protected $kelasId;

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

    public function collection(Collection $rows)
    {
        foreach ($rows as $row) {
            $nisn = $row['nisn'] ?? null;
            if (!$nisn) continue;

            $siswa = Siswa::where('nisn', $nisn)->first();
            if (!$siswa) continue;

            SiswaKelas::firstOrCreate([
                'siswa_id' => $siswa->id,
                'kelas_id' => $this->kelasId,
            ]);

            $kelasMapelIds = KelasMapel::where('kelas_id', $this->kelasId)->pluck('id');
            foreach ($kelasMapelIds as $kelasMapelId) {
                Nilai::firstOrCreate([
                    'siswa_id' => $siswa->id,
                    'kelas_mapel_id' => $kelasMapelId,
                ], [
                    's_nilai' => json_encode(array_fill_keys([
                        'sumatif_1','sumatif_2','sumatif_3','sumatif_4','sumatif_5',
                        'sumatif_6','sumatif_7','sumatif_8','sumatif_9','sumatif_10'
                    ], 0))
                ]);
            }
        }
    }
}
