<?php

namespace App\Imports;

use App\Models\Siswa;
use App\Models\Nilai;
use Illuminate\Support\Collection;
use Illuminate\Validation\ValidationException;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class SiswaNilaiImport implements ToCollection, WithHeadingRow
{
    protected $kelasMapelId;

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

    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;

            $nilai = Nilai::where([
                'siswa_id' => $siswa->siswa_id,
                'kelas_mapel_id' => $this->kelasMapelId,
            ])->first();

            $maxField = 10;
            if ($nilai && is_array($nilai->s_nilai)) {
                $maxField = count($nilai->s_nilai);
            }

            $dataNilai = $row->except(['nisn', 'nama'])->toArray();

            if (count($dataNilai) < $maxField) {
                throw ValidationException::withMessages([
                    'file' => "Gagal untuk NISN {$nisn}: jumlah kolom nilai di Excel (" . count($dataNilai) . ") lebih sedikit dari data sumatif yang sudah ada ($maxField).",
                ]);
            }

            foreach ($dataNilai as $key => $nilaiInput) {
                // Cek apakah bukan numerik (huruf, simbol)
                if (!is_numeric($nilaiInput)) {
                    throw ValidationException::withMessages([
                        'file' => "Gagal untuk NISN {$nisn}: di kolom nilai harus angka bulat, tidak boleh huruf/simbol.",
                    ]);
                }

                // Cek angka tidak bulat (misal 85.5)
                if (floor($nilaiInput) != $nilaiInput) {
                    throw ValidationException::withMessages([
                        'file' => "Gagal untuk NISN {$nisn}: di kolom nilai harus bilangan bulat tanpa koma.",
                    ]);
                }

            }

            $limitedData = array_slice($dataNilai, 0, $maxField, true);

            Nilai::updateOrCreate(
                [
                    'siswa_id' => $siswa->siswa_id,
                    'kelas_mapel_id' => $this->kelasMapelId,
                ],
                [
                    's_nilai' => $limitedData,
                ]
            );
        }
    }
}
