<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

class UserRolePermissionSeeder extends Seeder
{
    /**
     * @return void
     */

    public function run()
    {
        $default_user_value = [
            'email_verified_at' => now(),
            'password' => Hash::make('password'),
            'remember_token' => Str::random(10),
        ];

        // Ubah struktur ke multi-dimensional array
        $users_by_type = [
            'superadmin' => [],
        ];

        $users = [
            [
                'email' => 'superadmin@gmail.com',
                'name' => 'Super Admin',
                'type' => 'superadmin', 
            ],
        ];

        foreach ($users as $user_data) {
            $type = $user_data['type']; 
            unset($user_data['type']); 
            $user = User::create(array_merge($user_data, $default_user_value));
            
            // Tambahkan user ke array sesuai type
            $users_by_type[$type][] = $user;
        }

        
        $role_superadmin = Role::create(['name' => 'superadmin']);
      

        $permissions = [
            'create user',
            'edit user',
            'delete user',
            'read user',
        ];

        foreach ($permissions as $permission) {
            Permission::create(['name' => $permission]);
        }

        // Assign roles ke semua user berdasarkan type
        foreach ($users_by_type['superadmin'] as $user) {
            $user->assignRole($role_superadmin);
        }
        
    }
     
}
