<?php

namespace App\Imports;

use App\Models\Siswa;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Maatwebsite\Excel\Concerns\ToCollection;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Concerns\WithBatchInserts;

class SiswaImport implements ToCollection, WithHeadingRow, WithChunkReading, WithBatchInserts
{
    public function collection(Collection $rows)
    {
        foreach ($rows as $data) {
            if (!$data['nama_siswa']) continue; // skip baris kosong

            DB::transaction(function () use ($data) {
                $firstName = strtolower(explode(' ', trim($data['nama_siswa']))[0]);

                $username = $firstName;
                $counter = 1;
                while (User::where('username', $username)->exists()) {
                    $username = $firstName . $counter;
                    $counter++;
                }

                $user = User::create([
                    'name' => $data['nama_siswa'],
                    'username' => $username,
                    'password' => Hash::make('konseling25'),
                ]);

                Siswa::create([
                    'nama_siswa' => $data['nama_siswa'],
                    'nis' => $data['nis'],
                    'tempat_lahir' => $data['tempat_lahir'],
                    'tanggal' => $data['tanggal'],
                    'jenis_kelamin' => $data['jenis_kelamin'],
                    'agama' => $data['agama'],
                    'pendik_sebelumnya' => $data['pendik_sebelumnya'],
                    'jmlh_sodara' => $data['jmlh_sodara'],
                    'alamat' => $data['alamat'],
                    'nama_ayah' => $data['nama_ayah'],
                    'nama_ibu' => $data['nama_ibu'],
                    'pekerjaan_ayah' => $data['pekerjaan_ayah'],
                    'pekerjaan_ibu' => $data['pekerjaan_ibu'],
                    'kelas' => $data['kelas'],
                    'tahun_pelajaran' => $data['tahun_pelajaran'],
                    'id_guru' => $data['id_guru'],
                    'id_user' => $user->id,
                ]);

                $user->assignRole('Siswa');
            });
        }
    }

    public function chunkSize(): int
    {
        return 100;
    }

    public function batchSize(): int
    {
        return 100;
    }
}
