<?php

namespace Database\Seeders;

use App\Models\Kelas;
use App\Models\Siswa;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;

class SiswaSeeder extends Seeder
{
    public function run(): void
    {
        $kelas = Kelas::where('nama', 'IX-A')->first();
        if (!$kelas) return;

        $siswaData = [
            ['nis' => '2024001', 'nama' => 'Ahmad Rizki',      'jk' => 'L', 'email' => 'ahmad.rizki@siswa.com'],
            ['nis' => '2024002', 'nama' => 'Siti Aminah',      'jk' => 'P', 'email' => 'siti.aminah@siswa.com'],
            ['nis' => '2024003', 'nama' => 'Budi Santoso',     'jk' => 'L', 'email' => 'budi.santoso@siswa.com'],
            ['nis' => '2024004', 'nama' => 'Dewi Rahayu',      'jk' => 'P', 'email' => 'dewi.rahayu@siswa.com'],
            ['nis' => '2024005', 'nama' => 'Fajar Nugroho',    'jk' => 'L', 'email' => 'fajar.nugroho@siswa.com'],
        ];

        foreach ($siswaData as $data) {
            $user = User::firstOrCreate(['email' => $data['email']], [
                'name'     => $data['nama'],
                'password' => Hash::make('siswa123'),
                'role'     => 'siswa',
                'is_aktif' => true,
            ]);

            Siswa::firstOrCreate(['user_id' => $user->id], [
                'kelas_id'     => $kelas->id,
                'nis'          => $data['nis'],
                'nama'         => $data['nama'],
                'jenis_kelamin'=> $data['jk'],
            ]);
        }

        $kelas->update(['jumlah_siswa' => Siswa::where('kelas_id', $kelas->id)->count()]);
    }
}
