<?php

namespace App\Imports;

use App\Models\Guru;
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 GuruImport implements ToCollection, WithHeadingRow, WithChunkReading, WithBatchInserts
{
    public function collection(Collection $rows)
    {
        foreach ($rows as $data) {
            if (!$data['nama_guru']) continue; // skip baris kosong

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

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

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

                Guru::create([
                    'nip' => $data['nip'],
                    'nama_guru' => $data['nama_guru'],
                    'jabatan' => $data['jabatan'],
                    'jenis_kelamin' => $data['jenis_kelamin'],
                    'id_user' => $user->id,
                ]);

                $jabatan = $data['jabatan'];

                if (
                    Str::startsWith($jabatan, 'Wali Kelas X') ||
                    Str::startsWith($jabatan, 'Wali Kelas XI') ||
                    Str::startsWith($jabatan, 'Wali Kelas XII')
                ) {
                    $user->assignRole('WaliKelas');
                } elseif (Str::contains($jabatan, 'Guru BK')) {
                    $user->assignRole('GuruBK');
                } elseif (Str::contains($jabatan, 'Kepala Sekolah')) {
                    $user->assignRole('KepalaSekolah');
                } elseif (Str::contains($jabatan, 'Guru Matapelajaran')) {
                    $user->assignRole('GuruPengajar');
                }
            });
        }
    }

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

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