<?php

namespace App\Imports;

use App\Models\KehadiranSiswa;
use App\Models\User;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Illuminate\Validation\ValidationException;

class KehadiranSiswaImport implements ToCollection
{
    protected $bulanKehadiranId;

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

     public function collection(Collection $rows)
    {
        $rows->shift();

        foreach ($rows as $i => $row) {
            $rowNumber = $i + 2;

            $nisn = trim($row[1]);

            $user = User::whereHas('siswa', function ($q) use ($nisn) {
                $q->where('nisn', $nisn);
            })->first();

            if (!$user) {
                throw ValidationException::withMessages([
                    'import_error' => "Data tidak valid di baris {$rowNumber}: NISN {$nisn} tidak ditemukan.",
                ]);
            }

            foreach ([2, 3, 4] as $col) {
                if (!is_numeric($row[$col])) {
                    $field = ['Sakit', 'Izin', 'Alpha'][$col - 2];
                    throw ValidationException::withMessages([
                        'import_error' => "Kolom {$field} di baris {$rowNumber} harus berupa angka.",
                    ]);
                }
            }

            KehadiranSiswa::updateOrCreate(
                [
                    'bulan_kehadiran_id' => $this->bulanKehadiranId,
                    'siswa_id' => $user->id
                ],
                [
                    'sakit' => (int) $row[2],
                    'izin'  => (int) $row[3],
                    'alpha' => (int) $row[4],
                ]
            );
        }
    }
}
