<?php

namespace Database\Seeders;

use App\Models\Division;
use App\Models\User;
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Role;

class UserSeeder extends Seeder
{
    public function run(): void
    {
        $divisions = Division::pluck('id', 'name');

        $users = [
            ['name' => 'Budi Santoso',   'email' => 'ketua@persegi.id',    'role' => 'ketua',     'division' => 'Humas'],
            ['name' => 'Siti Rahayu',    'email' => 'bendahara@persegi.id','role' => 'bendahara', 'division' => 'Pendidikan'],
            ['name' => 'Ahmad Fauzi',    'email' => 'pengurus@persegi.id', 'role' => 'pengurus',  'division' => 'Olahraga'],
            ['name' => 'Dewi Lestari',   'email' => 'auditor@persegi.id',  'role' => 'auditor',   'division' => 'Seni & Budaya'],
            ['name' => 'Rizky Pratama',  'email' => 'anggota1@persegi.id', 'role' => 'anggota',   'division' => 'Lingkungan'],
            ['name' => 'Nur Hidayah',    'email' => 'anggota2@persegi.id', 'role' => 'anggota',   'division' => 'Humas'],
        ];

        // super_admin mendapat semua permission via Shield config
        $superAdmin = User::firstOrCreate(
            ['email' => 'admin@admin.com'],
            [
                'name'     => 'Super Admin',
                'password' => bcrypt('admin'),
                'phone'    => '08123456789',
                'status'   => 'aktif',
            ]
        );

        $superAdmin->assignRole('super_admin');

        foreach ($users as $data) {
            $user = User::firstOrCreate(
                ['email' => $data['email']],
                [
                    'name'        => $data['name'],
                    'password'    => bcrypt('password'),
                    'phone'       => '08' . rand(100000000, 999999999),
                    'address'     => 'Desa Karangdadap, Kalibagor, Banyumas',
                    'division_id' => $divisions[$data['division']] ?? null,
                    'status'      => 'aktif',
                ]
            );

            $user->syncRoles([$data['role']]);
        }
    }
}
