<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\User;
use App\Services\DummyDataService;
use Illuminate\Support\Facades\Hash;

class UserSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $allSiswa = DummyDataService::getAllSiswa();

        foreach ($allSiswa as $data) {
            $nomorInduk = $data['nisn'] ?? $data['nip'] ?? null;
            
            if (!$nomorInduk) continue;

            User::updateOrCreate(
                ['nomor_induk' => $nomorInduk],
                [
                    'id' => $data['id'],
                    'name' => $data['nama_lengkap'],
                    'nama_lengkap' => $data['nama_lengkap'],
                    'email' => $data['email'],
                    'password' => Hash::make($data['password']),
                    'phone' => $data['nomor_hp'] ?? null,
                    'role' => $data['role'],
                    'is_banned' => $data['is_banned'] ?? false,
                    'kelas' => $data['kelas'] ?? null,
                    'golongan' => $data['golongan'] ?? null,
                ]
            );
        }

        // Default admin
        User::updateOrCreate(
            ['nomor_induk' => 'admin'],
            [
                'name' => 'Admin Perpustakaan',
                'nama_lengkap' => 'Admin Perpustakaan',
                'email' => 'admin@smkn1perpus.sch.id',
                'password' => Hash::make('password'),
                'role' => 'penjaga perpus',
            ]
        );

        // Generate 95 additional users to reach around 100 total
        $additionalCount = 95;
        for ($i = 0; $i < $additionalCount; $i++) {
            $nomorInduk = fake()->unique()->numerify('##########');
            $name = fake()->name();
            
            $adminId = User::where('role', 'penjaga perpus')->first()?->id ?? 2;
            
            \App\Models\MasterInduk::create([
                'user_id' => $adminId,
                'nomor_induk' => $nomorInduk,
                'role' => 'siswa',
                'nama_pemilik' => $name,
            ]);

            User::create([
                'name' => $name,
                'nama_lengkap' => $name,
                'email' => fake()->unique()->safeEmail(),
                'password' => Hash::make('password'),
                'nomor_induk' => $nomorInduk,
                'role' => 'siswa',
                'phone' => fake()->phoneNumber(),
                'kelas' => fake()->randomElement(['X RPL', 'XI RPL', 'XII RPL', 'X TKJ', 'XI TKJ', 'XII TKJ']),
                'golongan' => fake()->randomElement(['A', 'B', 'C']),
            ]);
        }
    }
}
