<?php

namespace App\Imports;

use App\Models\Buku;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\SkipsOnError;
use Maatwebsite\Excel\Concerns\SkipsErrors;

class BukuImport implements ToModel, WithHeadingRow, SkipsOnError
{
    use SkipsErrors;

    public function model(array $row)
    {
        // Skip baris kosong atau kod buku sudah wujud
        if (empty($row['kod_buku']) || Buku::where('kod_buku', strtoupper($row['kod_buku']))->exists()) {
            return null;
        }

        return new Buku([
            'kod_buku'       => strtoupper($row['kod_buku']),
            'judul'          => $row['judul'] ?? '',
            'darjah'         => $row['darjah'] ?? '',
            'jenis_sekolah'  => !empty($row['jenis_sekolah']) ? strtoupper($row['jenis_sekolah']) : null,
        ]);
    }
}
