<?php

namespace App\Imports;

use App\Models\Siswa;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithValidation;

class SiswaImport implements ToCollection, WithHeadingRow, WithValidation
{
    public int $imported = 0;
    public array $failed = [];

    public function collection(Collection $rows): void
    {
        foreach ($rows as $index => $row) {
            try {
                Siswa::updateOrCreate(
                    ['nisn' => (string) $row['nisn']],
                    [
                        'nama'             => $row['nama'],
                        'kelas'            => $row['kelas'],
                        'jurusan'          => $row['jurusan'] ?? null,
                        'status_kelulusan' => strtolower($row['status_kelulusan']) === 'lulus' ? 'lulus' : 'tidak_lulus',
                        'tahun_ajaran'     => $row['tahun_ajaran'] ?? '2024/2025',
                    ]
                );
                $this->imported++;
            } catch (\Exception $e) {
                $this->failed[] = ['row' => $index + 2, 'error' => $e->getMessage()];
            }
        }
    }

    public function rules(): array
    {
        return [
            'nisn' => ['required'],
            'nama' => ['required'],
            'kelas' => ['required'],
        ];
    }

    public function customValidationMessages(): array
    {
        return [
            'nisn.required' => 'Kolom NISN wajib diisi.',
            'nama.required' => 'Kolom Nama wajib diisi.',
            'kelas.required' => 'Kolom Kelas wajib diisi.',
        ];
    }
}
