<?php

namespace App\Imports;

use App\Models\Siswa;
use App\Models\SiswaKelas;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class SiswaKelasImport implements ToModel, WithHeadingRow
{
    protected $kelasId;

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

    public function model(array $row)
    {
        $nisn = $row['nisn'] ?? null;
        if (!$nisn) {
            Log::warning("Import SiswaKelas gagal, NISN kosong.");
            return null;
        }

        $siswa = Siswa::where('nisn', $row['nisn'])->first();

        if (!$siswa || !$siswa->user) {
            throw new \Exception("Siswa tidak ditemukan dengan NISN {$row['nisn']} atau user-nya tidak ditemukan.");
        }

        $userId = $siswa->siswa_id;

        $exist = SiswaKelas::where('kelas_id', $this->kelasId)
            ->where('siswa_id', $userId)
            ->exists();

        if ($exist) {
            Log::info("Duplikat SiswaKelas: kelas_id={$this->kelasId}, siswa_id={$siswa->user_id}");
            return null;
        }

        return new SiswaKelas([
            'kelas_id' => $this->kelasId,
            'siswa_id' => $userId,
        ]);
    }
}
