<?php
namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

class RoleSeeder extends Seeder
{
    public function run()
    {
        // Clear cached roles and permissions
        app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();

        // Define permissions using snake_case
        $permissions = [
            // Super Admin Permissions
            'manage_all_schools', 'create_school', 'edit_school', 'delete_school',

            // School Admin Permissions
            'manage_school_settings', 'manage_teachers', 'manage_students', 
            'manage_parents', 'manage_classes', 'manage_subjects', 
            'manage_exams', 'manage_attendance',

            // Teacher Permissions
            'manage_own_classes', 'manage_grades', 'take_attendance',

            // Student Permissions
            'view_own_grades', 'view_timetable', 'view_attendance',

            // Parent Permissions
            'view_children_grades', 'view_children_attendance', 'view_children_timetable'
        ];

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

        // Create Roles
        // $superAdmin = Role::firstOrCreate(['name' => 'super_admin']);
        $schoolAdmin = Role::firstOrCreate(['name' => 'school_admin']);
        $teacher = Role::firstOrCreate(['name' => 'teacher']);
        $student = Role::firstOrCreate(['name' => 'student']);
        $parent = Role::firstOrCreate(['name' => 'parent']);

        // Assign permissions to roles
        // $superAdmin->givePermissionTo([
        //     'manage_all_schools', 'create_school', 'edit_school', 'delete_school'
        // ]);

        $schoolAdmin->givePermissionTo([
            'manage_school_settings', 'manage_teachers', 'manage_students',
            'manage_parents', 'manage_classes', 'manage_subjects',
            'manage_exams', 'manage_attendance'
        ]);

        $teacher->givePermissionTo([
            'manage_own_classes', 'manage_grades', 'take_attendance'
        ]);

        $student->givePermissionTo([
            'view_own_grades', 'view_timetable', 'view_attendance'
        ]);

        $parent->givePermissionTo([
            'view_children_grades', 'view_children_attendance', 'view_children_timetable'
        ]);
    }
}
