<?php

namespace Database\Seeders;

use App\Models\User;
use App\Models\SiswaProfile;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class SiswaSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $students5A = [
            ['name' => 'Ahmad Fauzi', 'nis' => '25001'],
            ['name' => 'Siti Aisyah', 'nis' => '25002'],
            ['name' => 'Muhammad Rizki', 'nis' => '25003'],
            ['name' => 'Nurul Hidayah', 'nis' => '25004'],
            ['name' => 'Fajar Ramadhan', 'nis' => '25005'],
            ['name' => 'Aulia Putri', 'nis' => '25006'],
            ['name' => 'Dimas Pratama', 'nis' => '25007'],
            ['name' => 'Salsa Nabila', 'nis' => '25008'],
            ['name' => 'Reza Maulana', 'nis' => '25009'],
            ['name' => 'Tiara Maharani', 'nis' => '25010'],
        ];

        $students5B = [
            ['name' => 'Andi Saputra', 'nis' => '25011'],
            ['name' => 'Nabila Zahra', 'nis' => '25012'],
            ['name' => 'Yoga Pratama', 'nis' => '25013'],
            ['name' => 'Citra Lestari', 'nis' => '25014'],
            ['name' => 'Bagas Firmansyah', 'nis' => '25015'],
            ['name' => 'Intan Permata', 'nis' => '25016'],
            ['name' => 'Farhan Akbar', 'nis' => '25017'],
            ['name' => 'Alya Safitri', 'nis' => '25018'],
            ['name' => 'Rizky Kurniawan', 'nis' => '25019'],
            ['name' => 'Putri Ananda', 'nis' => '25020'],
        ];

        $this->createStudents($students5A, '5A');
        $this->createStudents($students5B, '5B');
    }

    private function createStudents(array $students, string $kelas): void
    {
        foreach ($students as $student) {
            // Generate clean email e.g. ahmadfauzi@sipena.com
            $email = Str::lower(Str::replace(' ', '', $student['name'])) . '@sipena.com';
            
            // Create user
            $user = User::updateOrCreate(
                ['email' => $email],
                [
                    'name' => $student['name'],
                    'password' => Hash::make('password'),
                    'role' => 'siswa',
                ]
            );

            // Create or update SiswaProfile
            SiswaProfile::updateOrCreate(
                ['user_id' => $user->id],
                [
                    'nis' => $student['nis'],
                    'nama' => $student['name'],
                    'kelas' => $kelas,
                ]
            );
        }
    }
}
